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

2023-12-21

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

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

如何在 Rails 控制器中通过使用 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails媒体文件流通过send_data或send_file方法接受字节范围请求 的相关文章

随机推荐