0


vue使用文件流和url下载文件

// 改为使用后台返回url下载文件

方法1:这个会导致在点击下载按钮的时候,页面会跳转到奇怪的url。

window.location.href = row.downloadUrl

方法2:点击下载按钮,不会在新窗口打开。

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()

// 后台返回文件流下载文件

 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)

}

}


本文转载自: https://blog.csdn.net/qq_42080594/article/details/128723155
版权归原作者 程序媛之博客 所有, 如有侵权,请联系我们删除。

“vue使用文件流和url下载文件”的评论:

还没有评论