[TOC]
### 1. 圖片下載
~~~
commonDownload(url, name) {
axios.get(url, { responseType: 'blob' }).then(
res => {
let fileName = null
if (res.data.type === 'image/jpeg') {
fileName = `${name}.jpg`
}
if (res.status === 200) {
if (typeof window.chrome !== 'undefined') {
// Chrome
const link = document.createElement('a')
link.href = window.URL.createObjectURL(res.data)
link.download = fileName
link.click()
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE
const blob = new Blob([res.data], { type: 'application/force-download' })
window.navigator.msSaveBlob(blob, fileName)
} else {
// Firefox
const file = new File([res.data], fileName, { type: 'application/force-download' })
window.open(URL.createObjectURL(file))
}
}
},
error => {
console.error('error', error)
}
)
}
~~~
### 2. 一般文件下載(含批量下載)
#### 2.1 `iframe`下載(不推薦,參照[`iframe`的優缺點](https://blog.csdn.net/baxiadsy_csdn/article/details/86245809))
**當沒有選擇時再用該方案**
> 該方案支持批量下載,但每個下載都會新增一個`iframe` `dom`元素
~~~
commonDownloadFunction(url) {
const iframe = document.createElement('iframe')
iframe.src = url
iframe.style.display = 'none'
document.body.appendChild(iframe)
setTimeout(() => {
iframe.remove()
}, 1000 * 60)
}
~~~
#### 2.2 `widow.location.assign`下載
> 適合于單文件下載,批量下載可能會只下載一個文件
> 不支持文件名修改,文件名由后臺提供
~~~
commonDownloadFunction(url) {
window.location.assign(url)
}
~~~
#### 2.3`a`標簽下載(最佳選擇)
方法1
> `download`屬性指明當前下載文件的文件名
> 這種方法亦只適合于單文件下載,批量下載可能會只下載一個文件
~~~
commonDownload(url, name) {
const link = document.createElement('a')
link.href = url
link.download = name
link.click()
}
~~~
方法2
>[warning] 設置`responseType`為`blob`,請求得到一個二進制數據流,通過`a`標簽直接放入本地
> 優點: 此方法支持批量下載,且可知當前下載文件是否存在
> 缺點: 需要給文件后綴名以告訴當前下載文件的保存類型(后綴名最好由后端提供)
eg: (本例中將后綴名寫死了,實際場景中一般不會這樣)
~~~
async commonDownload(url, name) {
try {
const res = await axios({
method: 'get',
url,
responseType: 'blob'
})
const link = document.createElement('a')
link.href = window.URL.createObjectURL(res.data)
link.download = `${name}.zip`
link.click()
} catch (error) {
console.error(`‘${name}’文件不存在或已刪除!`)
}
}
~~~