我对 JS 代码很陌生,只是接手了同事留下的工作。
当 Flask 代码使用 send_file 返回 zip 文件时,JS 端下载似乎无效。其他格式,如文本和 csv 都很好。
服务器代码片段:
@bp.route('/download_file', methods=['POST'])
@login_required
def download_file():
download_path = request.form.get("download_path")
if os.path.exists(download_path):
@after_this_request
def send_response(response):
return response
return send_file(download_path, as_attachment=True)
下载路径是位于我的服务器上的文件路径
块引用
JS代码如下,目标是用户点击下载按钮并下载文件。
$.post('/download_file', {'download_path' : download_path}).done(function(data) {
var blob =new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "my.zip";
link.click();
}).fail(function(data) {
alert("danger", "Can't find download file");
});
Zip 文件可以下载,但已损坏。我的极限前端调试经验显示 Blob 中的数据看起来很奇怪。感谢任何帮助和建议