Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k 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 Answer

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');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...