0

I want to create downloadable files and I did it. But when I want to download it in a download manager, I cant Pause/Resume it and it has to download the whole file.

Here is my code :

@app.route('/Media/music/<filename>', methods=['GET', 'POST'])
def Music(filename):
    return send_file('static//Media/music/'+filename, as_attachment=True)

|Flask and Python|

I would appreciate any help or reference. Thanks.

Revisto
  • 1,211
  • 7
  • 11

1 Answers1

2

You will have to retrieve the Range header if the browser is sending it and then open the byte range of the file and pass that to send_file as the file pointer:

partial_file = f.seek(start_of_byte_range)
...return send_file(partial_file, ....), 206

https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

https://stackoverflow.com/a/29376554/1399491

and make sure you respond with an HTTP 206 with the partial file range instead of the normal 200 or other HTTP code

Range header info

Here is a rough untested version of what this would look like:

from flask import request

@app.route('/Media/music/<filename>', methods=['GET', 'POST'])
def Music(filename):
    range_header = request.headers.get('Range')
    if range_header is not None:
        with open('static//Media/music/'+filename, 'rb') as f:
            partial_file = f.seek(range_header)
            return send_file(partial_file, as_attachment=True, conditional=True), 206
        raise Exception("Unknown exception")

    return send_file('static//Media/music/'+filename, as_attachment=True)
Alex W
  • 37,233
  • 13
  • 109
  • 109