需要使用axios和js-file-download組件
npm install js-file-download --save
npm install axios --save
import fileDownload from 'fileDownload'; // 引入fileDownload
import axios from 'axios'; // 引入axios
axios({
method: 'get',
url: 'xxxxxxx',
responseType: 'blob'
}).then(res => {
if(res.status == 200){
// res.headers['content-disposition'].substring(20)表示從響應(yīng)頭中獲取文件名
fileDownload(res.data,res.headers['content-disposition'].substring(20));
}else { // 下載文件失敗,解析json格式信息
let that = this;
var fileReader = new FileReader();
fileReader.readAsText(res.data); // 按字節(jié)讀取文件內(nèi)容,結(jié)果為文件的二進(jìn)制串
fileReader.onload = ()=>{
that.$notify.error(fileReader.result);
}
}
})
注意事項(xiàng):responseType:blob表示服務(wù)器返回的響應(yīng)類型是二進(jìn)制流,一般用于文件、視頻下載等場(chǎng)景。正常情況下后端返回二進(jìn)制數(shù)據(jù),當(dāng)后端服務(wù)器出錯(cuò)時(shí),往往會(huì)以json形式返回錯(cuò)誤信息,例如{"code":500,"msg":"未知異常"}。因?yàn)樵O(shè)置了blob類型,axios會(huì)強(qiáng)制把數(shù)據(jù)轉(zhuǎn)為blob,導(dǎo)致json格式的響應(yīng)沒(méi)辦法正常解析,需要使用FileReader對(duì)象來(lái)處理,F(xiàn)ileReader是一種異步讀取文件機(jī)制。FileReader提供了如下方法,大家根據(jù)需要自行選擇。
-
readAsArrayBuffer(file):按字節(jié)讀取文件內(nèi)容,結(jié)果用ArrayBuffer對(duì)象表示
-
readAsBinaryString(file):按字節(jié)讀取文件內(nèi)容,結(jié)果為文件的二進(jìn)制串
-
readAsDataURL(file):讀取文件內(nèi)容,結(jié)果用data:url的字符串形式表示文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-681284.html
-
readAsText(file,encoding):按字符讀取文件內(nèi)容,結(jié)果用字符串形式表示文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-681284.html
到了這里,關(guān)于vue axios實(shí)現(xiàn)下載文件及responseType:blob注意事項(xiàng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!