python flask send_file上传文件,通过 jquery.js下载

后端路由

@app.route("/download_data_file", methods=['GET', 'POST'])
def download_data_file():
    """
    浏览器下载文件接口
    通过 flask 的 send_file 发送文件
    """
    # 文件名(带扩展名)
    info = json.loads(request.form.get('data'))
    filename = info['filename']
    filepath = info['filepath']
    # print(filepath)
    # 文件大小
    fsize = os.path.getsize(filepath)

    response = make_response(send_file(filepath, as_attachment=True))
    response.headers["Content-Disposition"] = "attachment; filename={}".format(filename.encode().decode('latin-1'))
    response.headers["Content-length"] = fsize
    return response

前端 js

    function download_data_btn_func(obj) {
        let filename = test.txt;
        let filepath = ./test.txt;
        let params = {};
        params['filepath'] = filepath
        params['filename'] = filename
        console.log(params)
        //  注意:下载文件的ajax 请求 dataType不是'json'。去掉他,ajax会自动适配dataType 属性值
        $.ajax({
            url: '/download_data_file',
            type: 'post',
            data: { 'data': JSON.stringify(params) },
            success: function (result) {
                // 通过模拟一个a 元素下载文件
                let blob = new Blob([result]);
                let a = document.createElement('a');
                let url = window.URL.createObjectURL(blob);
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            },
            error: function (result) {
                console.log(result)
            }
        })
    }
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐