分段下载问题

dev_video
daiao 5 years ago
parent 49d93fb6aa
commit acc6ff0599

@ -21,9 +21,7 @@ class AttachmentsController < ApplicationController
if type_attachment == "inline"
send_file absolute_path(local_path(@file)),filename: @file.title, disposition: 'inline',type: 'application/pdf'
elsif type_attachment == "MP4"
response.header["Accept-Ranges"] = "bytes"
send_file absolute_path(local_path(@file)),filename: @file.title, disposition: 'inline',
type: @file.content_type.presence || 'application/octet-stream', x_sendfile: true
send_file_with_range absolute_path(local_path(@file)), disposition: 'inline', type: "video/mp4", range: true
else
send_file(absolute_path(local_path(@file)), filename: @file.title,stream:false, type: @file.content_type.presence || 'application/octet-stream')
end
@ -206,4 +204,27 @@ class AttachmentsController < ApplicationController
end
end
def send_file_with_range(path, options = {})
if File.exist?(path)
size = File.size(path)
if !request.headers["Range"]
status_code = 200 # 200 OK
offset = 0
length = File.size(path)
else
status_code = 206 # 206 Partial Content
bytes = Rack::Utils.byte_ranges(request.headers, size)[0]
offset = bytes.begin
length = bytes.end - bytes.begin
end
response.header["Accept-Ranges"] = "bytes"
response.header["Content-Range"] = "bytes #{bytes.begin}-#{bytes.end}/#{size}" if bytes
response.header["status"] = status_code
send_data IO.binread(path, length, offset), options
else
raise ActionController::MissingFile, "Cannot read file #{path}."
end
end
end

Loading…
Cancel
Save