简体   繁体   中英

Flask: force download pdf files to open in browser

I'm trying to download a PDF file using flask but I don't want the file to download as an attachment. I simply want it to appear in the user's browser as a separate webpage. I've tried passing the as_attachment=False option to the send_from_directory method but no luck.

Here is my function so far:

@app.route('/download_to_browser')
def download_to_browser(filename):
    return send_from_directory(directory=some_directory,
                               filename=filename,
                               as_attachment=False)

The function works in the sense that the file is downloading to my computer but I'd much rather just display it in the browser (and let the user download the file if they want to).

I read here I need to change the content-disposition parameter but I'm not sure how that can be done efficiently (perhaps using a custom response?). Any help?

Note: I'm not using Flask-Uploads at the moment but I probably will down the line.

You can try to add the mimetype parameter to send_from_directory :

return send_from_directory(directory=some_directory,
                           filename=filename,
                           mimetype='application/pdf')

That works for me, at least with Firefox.

If you need more control over headers, you can use a custom response, but you will lose the advantages of send_file() (I think it does something clever to serve the file directly from the webserver.)

with open(filepath) as f:
    file_content = f.read()

response = make_response(file_content, 200)
response.headers['Content-type'] = 'application/pdf'
response.headers['Content-disposition'] = ...

return response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM