在JS客户端上从Flask服务器接收xlsx文件



在我的客户机上,用户单击一个按钮,然后调用下面的函数。我遵循了StackOverflow上关于为文件创建url然后下载它的一些其他问题的代码:

export const exportData = async (checked) => {
let checked_arr = await exportDataHelper(checked)
try {
const res = await axios.post(local + "/get-files", checked_arr);
const url = URL.createObjectURL(res.data)
const link = document.createElement('a')
link.download = true;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link)
return res.data;
} catch (err) {
return err;
}
}

我的Flask服务器从我的JS客户端接收一些数据,并根据这些数据创建一个excel文件。作为对客户端的响应,我通过Flask的send_file:

发送excel文件
@app.route("/get-files", methods=['POST'])
def get_files():
if request.method == "POST":
..Creating excel file here..
try:
return send_file("newOutput.xlsx", as_attachment=True)
except FileNotFoundError as e:
return json.jsonify(message="Failed"), 404
else:
return json.jsonify(message="Failed"), 500
return json.jsonify(message="Failed"), 500

当我做console.log(res.data)时,我看到一些像PK����������?�a]I:O�����������[Content_Types].xml���n�0�E�����*1tQU��E������一样的胡言乱语。它比较长,但我就不粘贴了

但是JS代码之后什么都不做。事实上,在我创建const url后,我尝试记录一些东西到控制台,没有任何东西被记录,就像它被困在那里一样。任何帮助吗?我正在尝试在客户端下载文件。

这是为将来遇到这个问题的人准备的。我没有用其他文件类型(如.png .jpeg)测试这个答案。文本文件或任何其他类型以外的。xlsx,但我认为它仍然会工作,只要你改变mimetype

我最终将我的请求分开,一个POST请求将数据从我的JS客户端发送到我的Flask服务器。另一个FETCH请求请求创建的.xlsx文件。

JS/反应代码:

export const exportData = async (checked) => {
let checked_arr = await exportDataHelper(checked)
try {
const res = await axios.post(local + "/get-files", checked_arr);
return res;
} catch (err) {
return err;
}
}
export const fetchOutput = async () => {
await fetch(local + '/fetch-output').then(res => res.blob()).then(blob=> {
var file = new Blob([blob], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
var url = URL.createObjectURL(file)
var link = document.createElement('a')
link.download = "newOutput.xlsx";
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link)
})
}

Python/瓶代码:

@app.route("/get-files", methods=['POST'])
def get_files():
if request.method == "POST":
...some irrelevant code...
res = create_output_excel(result)
if res:
try:
return json.jsonify(message="Success"), 200
except FileNotFoundError as e:
return json.jsonify(message="Failed"), 404
else:
return json.jsonify(message="Failed"), 500
return json.jsonify(message="Failed"), 500
@app.route("/fetch-output")
def fetch_output():
return send_file("newOutput.xlsx", mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

在我的例子中,输出文件总是有相同的名称,所以当然,如果你的是变量,那么你必须对它做适当的更改。

最新更新