【发布时间】: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")
但是什么都没有发生。图像没有被下载。但是,图像正在服务器上创建并且没有损坏
我该如何解决这个问题?还有其他方法可以做我想做的事吗?
【问题讨论】:
-
如果您尝试获取 ajax 请求以将某些内容作为可下载附件进行处理,则需要使用以下内容:stackoverflow.com/questions/32545632/…
标签: javascript python-3.x flask httprequest fetch-api