我正在尝试解决从(Flask)服务器收到(Axios)Ajax请求后如何打开文件下载对话框。
目前在我使用的客户端上:
<script>
export default {
...
exportCSV: function() {
axios.post('/exportdata',
{
data: this.data,
},
{
headers: {
'Content-Type': ' text/html; charset=utf-8'
}
}
)
.then((response) => {
var headers = response.headers
var blob = new Blob([response.data], {type: headers['content-type']})
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'Filename'
link.click()
})
.catch(e => {
console.log('Error')
})
}
}
在我正在使用的服务器上:
return Response(
json.dumps({'json_data': my_data}, cls=MyEncoder),
status=200,
headers = {
"Content-Disposition": "attachment; filename={0}".format(filename),
}
mimetype="application/csv")
我从服务器得到一个响应OK,并且响应包含有效的头数据,我只是无法打开文件下载对话框。
任何线索?
答案 0 :(得分:0)
您必须添加 responseType
axios(url: 'http://localhost:5000/exportdata',
method: 'GET',
responseType: 'blob', // important
}
)
.then((response) => {
const blob = new Blob([response.data])
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = 'file.txt'
link.click()
URL.revokeObjectURL(link.href) // for firefox
})