From acc6ff0599a980fecd099dadb856c95f5a9dff83 Mon Sep 17 00:00:00 2001 From: daiao <358551898@qq.com> Date: Thu, 6 Feb 2020 23:04:58 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=86=E6=AE=B5=E4=B8=8B=E8=BD=BD=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/attachments_controller.rb | 27 ++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/app/controllers/attachments_controller.rb b/app/controllers/attachments_controller.rb index 2485c44a7..bba33bd8e 100644 --- a/app/controllers/attachments_controller.rb +++ b/app/controllers/attachments_controller.rb @@ -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