// 改為使用后臺(tái)返回url下載文件
方法1:這個(gè)會(huì)導(dǎo)致在點(diǎn)擊下載按鈕的時(shí)候,頁面會(huì)跳轉(zhuǎn)到奇怪的url。
window.location.href = row.downloadUrl
方法2:點(diǎn)擊下載按鈕,不會(huì)在新窗口打開。
const downloadRes = async () => {
? ? ? ? let response = await fetch(row.downloadUrl)
? ? ? ? let blob = await response.blob()
? ? ? ? let objectUrl = window.URL.createObjectURL(blob)
? ? ? ? let a = document.createElement('a')
? ? ? ? a.href = objectUrl
? ? ? ? a.download = row.fileName
? ? ? ? a.click()
? ? ? ? a.remove()
? ? ? }
? ? ? downloadRes()
// 后臺(tái)返回文件流下載文件
? ?? fileDownload(row.id).then((res) => {
? ? ????????this.downloadFile(res, row.taskName)
? ? })
fileDownload是下載的接口地址,看下圖
export function fileDownload(id) {
return request({
url: '/vehicle/offlineFile/download/' + id,
method: 'get',
responseType: 'blob',
})
}
downloadFile方法代碼如下:
// 通用下載方法
export function downloadFile(data, filename) {
? const content = data
? const blob = new Blob([content], {
? ? type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' //文件類型
? })
? if ('download' in document.createElement('a')) {
? ? const elink = document.createElement('a')
? ? elink.download = filename
? ? elink.style.display = 'none'
? ? elink.href = URL.createObjectURL(blob)
? ? document.body.appendChild(elink)
? ? elink.click()
? ? URL.revokeObjectURL(elink.href)
? ? document.body.removeChild(elink)
? } else {
? ? navigator.msSaveBlob(blob, filename)
? }文章來源:http://www.zghlxwxcb.cn/news/detail-413676.html
}文章來源地址http://www.zghlxwxcb.cn/news/detail-413676.html
到了這里,關(guān)于vue使用文件流和url下載文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!