How to change downloading name in flask?

前端 未结 4 2211
名媛妹妹
名媛妹妹 2021-02-18 17:06

I have a small project which has to response some files. I know that using nginx will be better decision but that files a really small.

Part of my program:

4条回答
  •  不要未来只要你来
    2021-02-18 17:42

    In my case, setting the as_attachment and attachment_filename did not work because the Content-Disposition: attachment does not appear in the client-side copy of the response.

    If you have Flask-CORS enabled, you can initialize it with expose_headers set to a custom header that specifies the filename (ex. "x-suggested-filename"). Then add that header to the response.

    # In file where the Flask app instance is initialized
    app = Flask(__name__)
    CORS(app, expose_headers=["x-suggested-filename"])
    
    # In file with the download endpoint
    result = send_file("/full/path/to/some/file",
                       mimetype="text/plain", # use appropriate type based on file
                       as_attachment=True,
                       conditional=False)
    result.headers["x-suggested-filename"] = "use_this_filename.txt"
    return result
    

    Then, in the client-side download code, you can inspect the response headers to get the filename from the same custom header:

    # Using axios and FileSaver
    let response = await axios.get(downloadUrl, downloadConfig);
    let filename = response.headers["x-suggested-filename"];
    FileSaver.saveAs(response.data, filename);
    

提交回复
热议问题