目前a標(biāo)簽下載文件已經(jīng)成為主流,并且用戶體驗(yàn)較好,因此本人沒(méi)有對(duì)其他下載方式深入研究過(guò)。
1.同源url
同源且下載地址就是一個(gè)文件時(shí),直接設(shè)置a標(biāo)簽的href屬性為下載地址,并且為a標(biāo)簽添加download屬性即可。如果非同源url,那么這種方式會(huì)直接將文件在新的頁(yè)面打開(kāi),而非下載。
2.非同源url
這里介紹三種發(fā)送請(qǐng)求的方式和一種不發(fā)送請(qǐng)求的方式。以下4種方式都不會(huì)打開(kāi)文件而是直接下載,由于是發(fā)送網(wǎng)絡(luò)請(qǐng)求,因此需要在服務(wù)端解決跨域問(wèn)題才能使用這種方式。以下請(qǐng)求都以axios為例:
2.1利用Blob對(duì)象(推薦)
//url是下載地址,fileName是下載時(shí)的文件名
function downloadFileBlob(url,fileName){
axios.get(url, {responseType: 'blob'}).then(res=>{
console.log(res);
let url=URL.createObjectURL(res.data);
console.log(url);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
//download屬性可以設(shè)置下載到本地時(shí)的文件名稱,經(jīng)測(cè)試并不需要加文件后綴
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
//釋放內(nèi)存
URL.revokeObjectURL(url);
})
}
打印結(jié)果:

2.2利用base64
適用于很小的文件
//url是下載地址,fileName是下載時(shí)的文件名
function downloadFile(url,fileName){
axios.get(url, {responseType: 'blob'}).then(res=>{
console.log(res);
const a = document.createElement('a');
a.style.display = 'none';
a.href = URL.createObjectURL(res.data);
//download屬性可以設(shè)置下載到本地時(shí)的文件名稱,經(jīng)測(cè)試并不需要加文件后綴
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
}
打印結(jié)果:

2.3利用arraybuffer(不推薦)
其實(shí)也是轉(zhuǎn)為base64,只是更麻煩一些,需要根據(jù)響應(yīng)頭的content-type屬性手動(dòng)拼接base64字符串。而且btoa也是一個(gè)過(guò)時(shí)的api,因此不推薦使用
function downloadArraybuffer(url,fileName){
axios.get(url, {responseType: 'arraybuffer'}).then(res=>{
console.log(res);
let href='data:'+res.headers['content-type']+';base64,'+window.btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log(href);
const a = document.createElement('a');
a.style.display = 'none';
a.href = href;
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
}
打印結(jié)果:

2.4特殊情況,返回的數(shù)據(jù)type為application/octet-stream

這種情況下,直接使用a標(biāo)簽并在url后拼接'?response-content-type=application/octet-stream'字符串就能實(shí)現(xiàn)下載。文件名無(wú)法修改,content-disposition字段中下發(fā)的filename就是文件名。使用2.123的三種方式下載的文件沒(méi)有后綴。
function downloadFile(url,fileName){
const a = document.createElement('a');
a.style.display = 'none';
a.href = url+'?response-content-type=application/octet-stream';
a.download='';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
以上就是我對(duì)前端文件下載的總結(jié),可能理解不是很深刻,如有錯(cuò)誤歡迎指正
參考文獻(xiàn):
https://blog.csdn.net/love_aya/article/details/115211470
https://blog.csdn.net/weixin_46801282/article/details/123386264