ruby-on-rails - Rails媒体文件流通过send_data或send_file方法接受字节范围请求

标签 ruby-on-rails http-headers sendfile x-sendfile

我有以下问题。声音从公用文件夹中隐藏,导致只有某些用户有权访问声音文件。因此,我制定了某种方法,其作用类似于声音URL,但首先计算是否允许当前用户访问此文件。

该文件通过send_data方法发送。问题是,即使它能正常工作,我的工作也会非常缓慢...我用来播放声音的jplayer插件的开发人员告诉我,我应该能够接受字节范围请求以使其正常工作...

如何在Rails Controller 中通过使用send_data或send_file发送文件来做到这一点?

谢谢,
马库斯

最佳答案

我已经能够使用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)

关于ruby-on-rails - Rails媒体文件流通过send_data或send_file方法接受字节范围请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6759426/

相关文章:

c# - 如何使用curl对Web服务进行身份验证?

linux - linux write 和 sendfile 系统调用的区别

ruby-on-rails - 在 chrome 中通过 Ruby on Rails 播放 MP3

ruby-on-rails - bundle 执行 rake Assets :precompile

ruby-on-rails - Rake des 不知道如何构建任务 'compile' ,如何跟踪这个错误?

ruby-on-rails - ArticlesController 中的 Rails ActiveRecord::InvalidForeignKey#destroy

linux - 总是在 Linux 上将 sendfile 与 nginx 一起使用吗?

ruby-on-rails - 在 Ubuntu 中运行 rails s 命令时出错

http-headers - 某些防火墙是否可能修改 'Accept-Encoding' ?虽然在 Fiddler 中看起来还不错

php - 我可以向 simplexml_load_file 添加自定义 header 吗