上次說了,實現文件的上傳需要三步,那么實現文件的下載呢?
答:也是三步
第一步:獲取文件的 fileId (或者別的什么的,總之應該是代表這個文件的東西),各家后台需要的都不一樣
第二步:調用接口
this.$http({
url:this.HOST + api.download,
method:'post',
params:{
fileId:fileId //此處上傳第一步獲取到的 fileid
},
responseType:'arraybuffer' //此處注意請求頭
}).then(function(res){
var this = that
var fileName = that.files.name //此處獲取文件名稱
that.download(res.data,fileName) //此處跳轉到第三步
})
第三步:處理返回值,並下載
download (data,fileName) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data])) //創建下載鏈接
let link = document.createElement('a') //創建a標簽
link.style.display = 'none' //將a標簽隱藏
link.href = url //給a標簽添加下載鏈接
link.setAttribute('download', fileName) // 此處注意,要給a標簽添加一個download屬性,屬性值就是文件名稱 否則下載出來的文件是沒有屬性的,空白白
document.body.appendChild(link)
link.click() //執行a標簽
}