Javascript 使用Ajax和Flask下载Excel文件

Javascript 使用Ajax和Flask下载Excel文件,javascript,python,ajax,flask,Javascript,Python,Ajax,Flask,用户按下页面上表单中包含的按钮: <form id="form"> <input type="button" id="export" value="Export"/> </form> 在哪里 Flask应用程序如下所示: @app.route('/export') def export(): xl_file= '/absolute/path/to/excel/file.xlsx' return send_file(xl_file, a

用户按下页面上
表单
中包含的按钮:

<form id="form">
    <input type="button" id="export" value="Export"/>
</form>
在哪里

Flask应用程序如下所示:

@app.route('/export')
def export():
    xl_file= '/absolute/path/to/excel/file.xlsx'
    return send_file(xl_file, as_attachment=True, mimetype='application/vnd.ms-excel')
文件的文件内容将返回到浏览器(请参见下图),但文件本身不会作为附件返回

问题是,回调需要什么样的外观才能将响应作为文件附件接受?否则,需要进行哪些修改

(是的,我已经搜索并阅读了SE上的许多帖子。大多数都在讨论使用
表单.submit()
方法,但没有提供详细信息。我希望避免使用
表单.submit()
,因为
表单中还有其他无法提交的元素。)


您真的需要使用ajax吗?我发现ajax是一种使用flask下载excel文件的变通方法……但它对我不起作用。 我只需在“rb”模式下打开excel文件,并将mimetype更改为在windows中识别为excel文件。您的Flast只需要调用getPlotExcel()

你可以用烧瓶

@app.route('/uploads/',方法=['GET','POST'])
def下载(文件名):
从_目录返回发送_(directory='uploads',filename=filename)

我使用了一种不同的方法,而不是Ajax,我创建了一个函数,在每次选择更改href时使用一些参数来更新它,在本例中是国家/地区id

HTML:

因此,当您单击该按钮时,href已经更新。我的部分是:

@app.route('/export_excel')
def export_excel ():
     country_id = request.args.get('country_id')
     obj = class_calc.calc()
     file_excel = obj.generate_excel(country_id)
     return send_file(file_excel, as_attachment=True, cache_timeout=0)

工作正常。

不确定post是否有用。尝试在响应
标题中添加标题('Content-Disposition:attachment;filename=“name_of_excel_file.xls”)send\u file
方法中使用
as_attachment=True
mimetype='application/vnd.ms excel
具有相同的效果(我认为)。这会自动设置mimetime和头吗?
@app.route('/export')
def export():
    xl_file= '/absolute/path/to/excel/file.xlsx'
    return send_file(xl_file, as_attachment=True, mimetype='application/vnd.ms-excel')
@app.route("/getPlotExcel")
def getPlotExcel():
    excelDownload = open("sample.xlsx",'rb').read()
    return Response(
        excelDownload,
        mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        headers={"Content-disposition":
                 "attachment; filename=sample.xlsx"})
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    return send_from_directory(directory='uploads', filename=filename)
<a type="button" class="btn btn-sm" id="export-excel" href="#">Download</a>
function country_change(country_id)
{
   var param = "/export_excel?";
   param += "country_id=" + country_id;
   $("a[id='export-excel']").attr('href', param);
}
@app.route('/export_excel')
def export_excel ():
     country_id = request.args.get('country_id')
     obj = class_calc.calc()
     file_excel = obj.generate_excel(country_id)
     return send_file(file_excel, as_attachment=True, cache_timeout=0)