rails media file stream通过send_data或send_file方法接受字节范围请求

Mar*_*kus 9 ruby-on-rails x-sendfile http-headers sendfile

我有以下问题.声音在公共文件夹中隐藏,因为只有某些用户应该有权访问声音文件.所以我做了一个特定的方法,它就像一个声音网址,但首先计算,是否允许当前用户访问此文件.

该文件由send_data方法发送.问题是,如果它工作得很好我工作得很慢...我用来播放声音的jplayer插件的开发者告诉我,我应该能够接受字节范围请求以使其正常工作...

如何通过发送带有send_data或send_file的文件在rails控制器中执行此操作?

谢谢你,马库斯

小智 9

我已经能够使用send_file成功地提供文件了.虽然我有一个故障,寻找歌曲的早期部分会导致一个新的请求,使歌曲从0:00重新开始,而不是从搜索栏中的真实位置.这是我到目前为止为我工作的内容:

  file_begin = 0
  file_size = @media.file_file_size 
  file_end = file_size - 1

  if !request.headers["Range"]
    status_code = "200 OK"
  else
    status_code = "206 Partial Content"
    match = request.headers['range'].match(/bytes=(\d+)-(\d*)/)
    if match
      file_begin = match[1]
      file_end = match[1] if match[2] && !match[2].empty?
    end
    response.header["Content-Range"] = "bytes " + file_begin.to_s + "-" + file_end.to_s + "/" + file_size.to_s
  end
  response.header["Content-Length"] = (file_end.to_i - file_begin.to_i + 1).to_s
  response.header["Last-Modified"] = @media.file_updated_at.to_s

  response.header["Cache-Control"] = "public, must-revalidate, max-age=0"
  response.header["Pragma"] = "no-cache"
  response.header["Accept-Ranges"]=  "bytes"
  response.header["Content-Transfer-Encoding"] = "binary"
  send_file(DataAccess.getUserMusicDirectory(current_user.public_token) + @media.sub_path, 
            :filename => @media.file_file_name,
            :type => @media.file_content_type, 
            :disposition => "inline",
            :status => status_code,
            :stream =>  'true',
            :buffer_size  =>  4096)
Run Code Online (Sandbox Code Playgroud)

  • 我刚试过这个并且它有效.尽管这里实际上并不需要流选项(:stream和:buffer_size). (2认同)