ajax post下载flask文件流以及中文文件名问题(ajax async默认值)快来看

随心笔谈12个月前发布 admin
83 0


from urllib.parse import quote
@file.route(‘/download’, methods=[“POST”])
def download_file():
filename=’xx’ #文件名
filepath=’xx/xx’ #文件路径
res=make_response(send_file(filepath))
#自定义的一个header,方便前端取到名字
res.headers[‘filename’]=quote(filename.encode(‘utf-8’))
return res
javascript——以async异步fetch为例:

async function download() {
const res=await fetch(`http://xxx/file/download`, {
method: “POST”,
body: JSON.stringify({}), //body里面是要发送的数据
headers: { “Content-Type”: “application/json” },
responseType: ‘blob’
})

if (res.ok) {
const blData=await res.blob() //拿到blob数据
const urlObjData=window.URL.createObjectURL(new Blob([blData])) //创建url对象

//获取文件 进行下转码
const fileName=decodeURI(fileNameres.headers.get(‘filename’))

//创建a标签 点击a标签 达到下载目的
const link=document.createElement(‘a’)
link.href=https://www.jb51.net/article/urlObjData
link.download=fileName //下载文件的名字
document.body.appendChild(link)
link.click()

document.body.removeChild(link)
window.URL.revokeObjectURL(urlObjData);

//展示图片
//xxx.src=https://www.jb51.net/article/urlObjData
}
}

© 版权声明

相关文章