一般有三種方法:
方法一: 通過a標簽下載
// href為文件的存儲路徑或者地址,download為問文件名 <a href="/images/download.jpg" download="downloadFileName" />
優點:簡單方便。
缺點:這種下載方式只支持Firefox和Chrome不支持IE和Safari,兼容性不夠好。
方法二:通過window.location
window.location = 'http://127.0.0.1:8080/api/download?name=xxx&type=xxx'
優點:簡單方便。
缺點:只能進行get請求,當有token校驗的時候不方便。
方法三:通過請求后台接口
// download.js
import axios from 'axios'
export function download(type, name) {
axios({
method: 'post',
url: 'http://127.0.0.1:8080/api/download',
// headers里面設置token
headers: {
loginCode: 'xxx',
authorization: 'xxx'
},
data: {
name: name,
type: type
},
// 二進制流文件,一定要設置成blob,默認是json
responseType: 'blob'
}).then(res => {
const link = document.createElement('a')
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.setAttribute('download', `${name}.xlsx`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
}
