1.post請求上傳後對後端解析文件,然後下載
uploadSectionFile(param) {
const self = this;
//formData 爲upload必須對象,默認接收的對象值
//eslint-disable-next-line
const formData = new FormData();
formData.append('file', param.file);
axios
.post(self.uploadAction, formData, {
responseType: 'blob',
headers: {
'data-type': 'Buffer',
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
if (res) {
//eslint-disable-next-line
const blob = new Blob([res.data]);
//對於<a>標籤,只有 Firefox 和 Chrome(內核) 支持 download 屬性
//IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) {
//支持a標籤download的瀏覽器
const link = document.createElement('a')//創建a標籤
link.download = fileName//a標籤添加屬性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()//執行下載
URL.revokeObjectURL(link.href) //釋放url
document.body.removeChild(link)//釋放標籤
}else{
navigator.msSaveBlob(blob, fileName)
}
} else {
self.$message.warning('轉化word文件失敗,請檢查文件並且重試!');
}
})
.catch((err) => {
//err
});
},
2.get方式下載
axios
.get(requesturl, {
responseType: 'blob',//必填
headers: self.header//你的頭部信息,可選
})
.then(res => {
if (res) {
//eslint-disable-next-line
const blob = new Blob([res.data]);
//對於<a>標籤,只有 Firefox 和 Chrome(內核) 支持 download 屬性
//IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) {
//支持a標籤download的瀏覽器
const link = document.createElement('a')//創建a標籤
link.download = fileName//a標籤添加屬性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()//執行下載
URL.revokeObjectURL(link.href) //釋放url
document.body.removeChild(link)//釋放標籤
}else{
navigator.msSaveBlob(blob, fileName)
}
}
})
.catch((err) => {
//err
});
3.純post請求下載文件
downloadFile(param) {
const self = this;
axios({
method: 'post',
url: url + '?v=' + Math.random(),
responseType: 'blob',
headers: {
'Content-Type': 'application/json',
'data-type': 'Buffer'
},
data: JSON.stringify(param)
})
.then(res => {
if (res) {
//eslint-disable-next-line
const blob = new Blob([res.data]);
//對於<a>標籤,只有 Firefox 和 Chrome(內核) 支持 download 屬性
//IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) {
//支持a標籤download的瀏覽器
const link = document.createElement('a')//創建a標籤
link.download = fileName//a標籤添加屬性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()//執行下載
URL.revokeObjectURL(link.href) //釋放url
document.body.removeChild(link)//釋放標籤
}else{
navigator.msSaveBlob(blob, fileName)
}
} else {
self.$message.warning('轉化word文件失敗,請檢查文件並且重試!');
}
})
.catch((err) => {
//err
});
},
4.出現的問題以及解決辦法
如圖,設置responseType: 'blob'後,獲取的response仍然爲默認的json串,並且下載出來的文件會亂碼。
原因:
我這邊發現的原因是:mock模塊會影響原生的ajax請求,使得服務器返回的blob類型變成亂碼
解決:
去掉mockjs模塊,以及相關的調用