如何使用 Flask 和 React 下载 excel 文件?
我正在尝试下载 xlsx 文件。我发布一个 id 并使用它从数据库获取数据。然后我可以创建一个excel文件,但我无法下载它。
我的后端代码:
from flask import Flask
from flask import request, jsonify, make_response, json, send_file, redirect, url_for,send_from_directory
from bson.json_util import dumps
from flask_cors import CORS
import dbConnections.Test as db
import os
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}}, support_credentials=True)
@app.route("/test-report", methods=["POST"])
def downloadTestReport():
req = request.get_json();
results = db.GetTestResult(req)
return send_file('foo.xlsx', as_attachment=True)
if __name__ =="__main__":
app.run(debug=True)
我的前端代码:
let downloadReport = (e)=>{
if(e.field ==="downloadReport"){
const objId= {testId: e.row.objId};
axios.post('http://127.0.0.1:5000/test-report', objId)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
我的控制台上的结果:
我想下载返回的 Excel 文件。
I am trying to download xlsx file. I post an id and using it to get data from database. Then i can create an excel file but i couldn't download it.
My backend codes:
from flask import Flask
from flask import request, jsonify, make_response, json, send_file, redirect, url_for,send_from_directory
from bson.json_util import dumps
from flask_cors import CORS
import dbConnections.Test as db
import os
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}}, support_credentials=True)
@app.route("/test-report", methods=["POST"])
def downloadTestReport():
req = request.get_json();
results = db.GetTestResult(req)
return send_file('foo.xlsx', as_attachment=True)
if __name__ =="__main__":
app.run(debug=True)
And my frontend codes:
let downloadReport = (e)=>{
if(e.field ==="downloadReport"){
const objId= {testId: e.row.objId};
axios.post('http://127.0.0.1:5000/test-report', objId)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
The result on my console:
I wanna download excel file which is return.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了在代码中显示 Ethan 的注释,假设您的后端 Flask 代码按应有的方式发送 Excel 文件,您的前端代码应如下所示:
这是参考:
//https://stackoverflow.com/questions/41938718 /how-to-download-files-using-axios?noredirect=1&lq=1
如何从apireact.js下载excel响应
To show what Ethan's comment is in code, Assuming your backend flask code is sending the Excel file as it should, your frontend code should look like this:
This is in reference to:
//https://stackoverflow.com/questions/41938718/how-to-download-files-using-axios?noredirect=1&lq=1
How to download excel in response from api react.js