Rails send_file不播放mp4

时间:2012-11-07 23:24:29

标签: ruby-on-rails ruby video-streaming ruby-on-rails-3.2

我有一个Rails应用程序,可以保护上传的视频,将它们放入私人文件夹。

现在我需要播放这些视频,当我在控制器中执行此类操作时:

  def show
    video = Video.find(params[:id])
    send_file(video.full_path, type: "video/mp4", disposition: "inline")
  end

然后在/ videos /:打开浏览器(Chrome或FF),不播放视频。

如果我将相同的视频放在公共文件夹中,并像/video.mp4那样访问它,它就会播放。

如果我删除了dispositon:“inline”,它将下载视频,我可以从我的电脑上播放它。 webm视频也是如此。

我错过了什么?这可能吗?

1 个答案:

答案 0 :(得分:5)

要播放视频,我们必须为某些浏览器处理请求的byte range

解决方案1:使用send_file_with_range gem

简单的方法是让send_file_with_range gem修补send_file方法。

在Gemfile中包含gem

# Gemfile
gem 'send_file_with_range'

并为range: true提供send_file选项:

def show
  video = Video.find(params[:id])
  send_file video.full_path, type: "video/mp4", 
    disposition: "inline", range: true
end

The patch很短,值得一看。 但是,不幸的是,它对Rails 4.2没有用。

解决方案2:手动修补send_file

受宝石的启发,手动扩展控制器非常简单:

class VideosController < ApplicationController

  def show
    video = Video.find(params[:id])
    send_file video.full_path, type: "video/mp4",
      disposition: "inline", range: true
  end

private

  def send_file(path, options = {})
    if options[:range]
      send_file_with_range(path, options)
    else
      super(path, options)
    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

      send_data IO.binread(path, length, offset), options
    else
      raise ActionController::MissingFile, "Cannot read file #{path}."
    end
  end

end

进一步阅读

首先,我不知道stream: truerange: true之间的区别,我发现这个railscast非常有用:

http://railscasts.com/episodes/266-http-streaming