Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

关于文件导出的一个疑问

忘了说下前提了,我使用Content-Disposition的目的就是为了避免在ajax请求后还要做多余的动作,也就是想去掉then里面的操作

axios.get('/export').then(res)

如果后端设置如下响应头

app.get('/export', (req, res) => {

    res.set({
        Content-Type: 'application/octet-stream; charset=utf-8',
        Content-Disposition: attachment; filename="123.jpg"
    })
    
    res.send(file);
})

那么前端使用如下方式,或者使用form发起Post或者get请求,都能让浏览器自动保存文件

location.href = '/export'
<a href="/export" download="123.jpg">

但是,如果使用ajax发起get或者post请求,就不行,我猜想应该是ajax覆盖了浏览器自动保存的控制权,但是我找不到相关资料来佐证,有人知道吗?

    axios.get('/export')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

谢邀,试试这种方法

Axios({
    url: 'http://localhost/downloadFile',
    method: 'GET',
    responseType: 'blob', // Important
})
.then(({ data }) => {
    const downloadUrl = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', 'file.zip'); //any other extension
    document.body.appendChild(link);
    link.click();
    link.remove();
});

也可以使用第三方库:https://www.npmjs.com/package...

const FileDownload = require('js-file-download');

Axios({
  url: 'http://localhost/downloadFile',
  method: 'GET',
  responseType: 'blob', // Important
}).then((response) => {
    FileDownload(response.data, 'report.csv');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...