'PDF file sent from flask to client is empty when downloaded
I have a flask server that sends a pdf file with the send_file function. When I test this route on postman I can view and download the pdf. However when I try to download it through my React frontend the file is blank BUT with the correct amount of pages. I suppose the problem stems from my use of blob but I don't see how.
Server route
@app.route("/test", methods=["GET"])
def results():
if request.method == "GET":
return send_file("pdf-path", cache_timeout=0, as_attachment=True)
This route works fine when tested on postman. I can view the pdf
client side
axios.get(URL + '/test')
.then(function (response) {
if (response.status === 200) {
const type = 'application/pdf';
const file = new Blob([response.data], { type: type });
saveAs(file, "test.pdf");
}
}
)
Here I am using axios and file-saver. The file is downloaded but all the pages are empty.
Solution 1:[1]
Try this one,
from flask import send_file, send_from_directory
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
uploads = os.path.join(current_app.root_path, 'uploads') # uploads is a folder
return send_from_directory(directory=uploads, filename=filename)
send_from_directory - Most recommended method.
If you want to use send_file method,
@app.route("/get-csv/<path:filename>")
def get_csv(filename):
safe_path = safe_join(app.config["CLIENT_CSV"], filename)
try:
return send_file(safe_path, as_attachment=True)
except FileNotFoundError:
abort(404)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nanthakumar J J |
