当前位置:首页 » 《随便一记》 » 正文

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

2 人参与  2023年04月08日 19:05  分类 : 《随便一记》  评论

点击全文阅读


// 改为使用后台返回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)

  }

}


点击全文阅读


本文链接:http://zhangshiyu.com/post/58929.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1