【问题标题】:Download file from server with Flask and JS使用 Flask 和 JS 从服务器下载文件
【发布时间】:2020-06-19 16:56:42
【问题描述】:

当用户单击特定按钮时,我正在尝试下载文件。该文件是按下所述按钮时创建的图像。我想要的是,它应该自动下载客户端设备上的图像。

我在服务器代码上使用 Flask,理想情况下,Flask 的 send_file 函数应该会触发此自动下载,因为它添加了 Content-Disposition 标头。

在客户端,我有一个 JS 代码,它使用 fetch API 向服务器发送一个带有一些数据的 POST 请求,用于生成要下载的图像。

这是JS代码:

function make_image(text){
    const json={
        text: text
    };
    const options={
        method: "POST",
        body: JSON.stringify(json),
        headers:{
            'Content-Type':'application/json',
        }
    };

    fetch('/image',options)
        .then(res=>{
            res.json(); //Gives an error: Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
        }).catch(err=>console.log(err));
}

这是服务器上的 Python 代码:

@app.route('/image',methods=['POST'])
def generate_image():
    cont = request.get_json()
    t=cont['text']
    print(cont['text'])
    name = pic.create_image(t)
    time.sleep(2)
    return send_file(f"{name}.png",as_attachment=True,mimetype="image/png")

但是什么都没有发生。图像没有被下载。但是,图像正在服务器上创建并且没有损坏

我该如何解决这个问题?还有其他方法可以做我想做的事吗?

【问题讨论】:

标签: javascript python-3.x flask httprequest fetch-api


【解决方案1】:

您可以执行以下操作

return send_from_directory(dir, file_name, as_attachment=True)

这会将文件下载到用户的机器上。

编辑:

顺便说一句,如果您创建如下所示的 html 表单,则不需要 javascript。

<form action='action here' method='post'>
    <input type='submit'>
</form>

【讨论】:

  • 我也试过 send_from_directory ......它没有用。至于 HTML,我要发送的数据在不同的部分,所以我无法在表单中获取它
  • 好的。你能更具体地说明发生了什么吗?显示什么错误。这样做会很有帮助:app.run(debug=True)
  • 没有任何错误,我点击了按钮,没有任何反应
【解决方案2】:

由于@clockwatcher 提到了不同的question,我使用download.js 模块来处理图像的下载。

所以我的 JS 代码现在看起来像这样:

function make_image(text){
    const json={
        text: text
    };
    const options={
        method: "POST",
        body: JSON.stringify(json),
        headers:{
            'Content-Type':'application/json',
        }
    };

    fetch('/image',options)
        .then(res=>{
            return res.blob();
        }).then(blob=>{
            download(blob)
        }).catch(err=>console.log(err));
}

并且在 html 中添加了 script 标签:

&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"&gt;&lt;/script&gt;

Python 服务器代码没有变化。

现在可以了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多