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

后端 未结 4 1667
走了就别回头了
走了就别回头了 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:39

    I used Garrett's answer and modified it (including one or two bug fixes). I also used send_data instead of reading from a file:

      def stream_data data, options={}
        range_start = 0
        file_size = data.length
        range_end = file_size - 1
        status_code = "200"
    
        if request.headers["Range"]
          status_code = "206"
          request.headers['range'].match(/bytes=(\d+)-(\d*)/).try do |match|
            range_start = match[1].to_i
            range_end = match[2].to_i unless match[2]&.empty?
          end
          response.header["Content-Range"] = "bytes #{range_start}-#{range_end}/#{file_size}"
        end
    
        response.header["Content-Length"] = (range_end - range_start + 1).to_s
        response.header["Accept-Ranges"] = "bytes"
    
        send_data(data[range_start, range_end],
                  filename: options[:filename],
                  type: options[:type],
                  disposition: "inline",
                  status: status_code)
      end
    

提交回复
热议问题