點(diǎn)擊下載文件按鈕,獲取后端返回接口,根據(jù)請(qǐng)求頭自動(dòng)解析文件名稱,自動(dòng)識(shí)別文件類型后綴名,如果中文是iso-8859-1格式轉(zhuǎn)換為utf-8,否則下載不了.文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-733937.html
axios({
method: 'get',
url: 'http://your-backend-url/download',
responseType: 'blob',
}).then(response => {
// 獲取請(qǐng)求頭內(nèi)容
const contentDisposition = response.headers['content-disposition'];
// 文件名處理、格式處理
const encodedFilename = contentDisposition.split('filename=')[1];
// utf-8格式處理
// const decodedFilename = decodeURIComponent(encodedFilename);
// iso-8859-1格式處理
const decodedFilename = decodeURIComponent(escape(encodedFilename));
// 創(chuàng)建一個(gè) Blob 對(duì)象
const blob = new Blob([response.data], { type: response.headers['content-type'] });
// 創(chuàng)建一個(gè) URL 對(duì)象
const url = window.URL.createObjectURL(blob);
// 創(chuàng)建一個(gè)鏈接元素并模擬點(diǎn)擊以下載文件
const a = document.createElement('a');
a.href = url;
//文件名、后綴類型處理
a.download = decodedFilename;
document.body.appendChild(a);
a.click();
// 釋放內(nèi)存
window.URL.revokeObjectURL(url);
});
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-733937.html
到了這里,關(guān)于下載文件,自動(dòng)獲取后端返回文件名,并自動(dòng)識(shí)別文件格式,如果是iso-8859-1編碼轉(zhuǎn)換utf-8的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!