文件的下載:
1. 最簡(jiǎn)單的就是用地址下載
window.open(url)
url就是文件所在的地址
比如:http://....../system_files/teacher.xlsx
這樣下載會(huì)打開一個(gè)網(wǎng)頁(yè),為了不打開新網(wǎng)頁(yè),可以這樣做:
function(fileUrl){
const url = fileUrl
const form = document.createElement('form') // 創(chuàng)建一個(gè)form標(biāo)簽
form.method = 'get'
form.action = url
document.body.appendChild(form)
form.submit()
}
2.帶token的下載
我們需要用xhr給后端發(fā)送一個(gè)帶token的請(qǐng)求頭
downloadFile(filename, fileUrl, token) {
const xhr = new XMLHttpRequest()
const url = fileUrl
xhr.open('get', url, true)
xhr.setRequestHeader('Authorization', `Bearer ${token}`) // 給后端發(fā)送請(qǐng)求頭
xhr.responseType = 'blob'
xhr.onload = function(e) {
if (this.status === 200) {
const blob = this.response
// URL對(duì)象是硬盤(SD卡等)指向文件的一個(gè)路徑,
//如果我們做文件上傳的時(shí)候,想在沒(méi)有上傳服務(wù)器端的情況下看到上傳圖片的效果圖
//就可是以通過(guò)var url=window.URL.createObjectURL(obj.files[0]);獲得一個(gè)http格式的url路徑
//這個(gè)時(shí)候就可以設(shè)置到<img>中顯示了
//window.webkitURL和window.URL是一樣的,window.URL標(biāo)準(zhǔn)定義
//window.webkitURL是webkit內(nèi)核的實(shí)現(xiàn)(一般手機(jī)上就是使用這個(gè)),還有火狐等瀏覽器的實(shí)現(xiàn)。
const urlObject = window.URL || window.webkitURL || window
const export_blob = new Blob([blob])
const a = document.createElementNS('http://www.w3.org/1999/xhtml', 'a') // 利用a標(biāo)簽特性下載
const url = urlObject.createObjectURL(export_blob)
a.href = url
a.download = filename
a.click()
}
}
// 發(fā)送請(qǐng)求
xhr.send()
}