rails media file stream accept byte range request through send_data or send_file method

后端 未结 4 1666
走了就别回头了
走了就别回头了 2020-11-30 05:20

I have the following problem. Sounds are hidden from the public folder, cause there are only certain Users who should have access to the sound files. So I made a certain met

4条回答
  •  悲哀的现实
    2020-11-30 05:49

    I've been able to serve up the files with some success using send_file. Although I have one hitch, seeking to an earlier part of the song causes a new request which makes the song restart from 0:00 instead of the true location from the seekbar. This is what I have working for me so far:

      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)
    

提交回复
热议问题