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

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

    Another amended version - I was trying to download a zip file as binary content and this is what worked for me -

      def byte_range_response (request, response, content)
        file_begin = 0
        file_size = content.bytesize
        file_end = file_size - 1
    
        status_code = '206 Partial Content'
        match = request.headers['range'].match(/bytes=(\d+)-(\d*)/)
        if match
          file_begin = match[1]
          file_end = match[2] if match[2] && !match[2].empty?
        end
        content_length = file_end.to_i - file_begin.to_i + 1
        response.header['Content-Range'] = 'bytes ' + file_begin.to_s + '-' + file_end.to_s + '/' + file_size.to_s
        response.header['Content-Length'] = content_length.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_data get_partial_content(content, content_length, file_begin.to_i), type: 'application/octet-stream', status: status_code
      end
    
      def get_partial_content(content, content_length, offset)
        test_file = Tempfile.new(['test-file', '.zip'])
        test_file.puts(content)
        partial_content = IO.binread(test_file.path, content_length, offset)
        test_file.close
        test_file.unlink
        partial_content
      end
    

提交回复
热议问题