- 項目中需要實作二進制流檔案下載下傳,采用Blob方式
- 首先采用axios進行get請求. 代碼如下:
import axios from 'axios'
const instant = axios.create({
withCredentials: true,
timeout: 600000,
})
instant.get(common.url + "good/download?goodId=" + this.id, {
headers: {
'Authorization': common.token
},
responseType: 'blob', //二進制流
}).then(response => {
console.log(response.data)
this.download()
}, err => {
console.log(err)
}).catch((error) => {
console.log(error)
})
注意: 提醒下這裡headers中common.token 是登入cookie,大家可以根據下載下傳需求不用關注. (同時設定的 timeout:600000, 這個值可以根據下載下傳檔案大小來設定,我的檔案很大,如果設定時間短,遇到大檔案就會出現下載下傳逾時,與伺服器斷開. )
- 然後是this.download這個方法實作:
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
let blob = new Blob([response.data], {
type: 'application/vnd.ms-excel'
})
window.navigator.msSaveOrOpenBlob(blob,
new Date().getTime() + '.zip')
} else {
/* 火狐谷歌的檔案下載下傳方式 */
var blob = new Blob([response.data])
var downloadElement = document.createElement('a')
var href = window.URL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = new Date().getTime() + '.zip'
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
}
注意: 這裡的 response.data 就是上面axios網絡請求傳回res值. 同時代碼 window.navigator.msSaveOrOpenBlob(blob, new Date().getTime() + '.zip') 這裡第二個參數,就是自己需要命名下載下傳的檔案. 這裡用的時間值作為命名.
- 常見問題:
1. axios 網絡下載下傳逾時,與伺服器斷開. 上面提到了,将timeout值設定大些。我在這裡就是遇到此問題.
使用就這麼簡單,Vue項目出現問題,可以 進扣扣群交流:316567839