可以使用axios庫下載文件流赴恨。具體步驟如下:
后端通過URL地址或API接口將文件流傳遞給前端。
前端使用axios庫發(fā)送GET請求因篇,獲取文件流數(shù)據(jù)沪停。
在響應(yīng)攔截器中獲取文件流數(shù)據(jù),并創(chuàng)建一個(gè)Blob對象约计。
創(chuàng)建一個(gè)a標(biāo)簽诀拭,設(shè)置它的href屬性為Blob URL,download屬性為文件名病蛉,觸發(fā)點(diǎn)擊事件進(jìn)行下載炫加。
import axios from 'axios';
// 下載文件流
function downloadFile(url) {
axios({
method: 'GET',
url: url,
responseType: 'blob'
})
.then(response => {
// 獲取文件流數(shù)據(jù)
const blob = new Blob([response.data]);
// 創(chuàng)建a標(biāo)簽進(jìn)行下載
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = '文件名';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(error => {
console.log(error);
});
}