sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

【vue】前端下载文件自定义文件名称
https://blog.csdn.net/weixin_48200589/article/details/125067618

文件下载名称不想和后端提供的URL一样怎么办呢?

1.首先给按钮去绑定一个事件

按钮的处理

 <div  class="list-item-download"
    @click="downLoadArticle(item.url , item.title)
 </div>
  • 1
  • 2
  • 3

2.正常我们的下载处理方式

1.直接通过后端返回的url,给location.href就可以下载了,但是文件名字,就是后端返回的 ,不可以自定义

window.location.href = url
  • 1

3.自定义下载的文件名字

 onDownFile(url, filename) {
      this.getBlob(url, (blob) => {
        this.saveAs(blob, filename)
      })
},
getBlob(url, cb) {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', url, true)
      xhr.responseType = 'blob'
      xhr.onload = function() {
        if (xhr.status === 200) {
          cb(xhr.response)
        }
      }
      xhr.send()
},
 saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename)
      }
      else {
        var link = document.createElement('a')
        var body = document.querySelector('body')
        link.href = window.URL.createObjectURL(blob)
        link.download = filename
        link.style.display = 'none'
        body.appendChild(link)
        link.click()
        body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
      }
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
posted on 2023-06-13 19:39  sunny123456  阅读(1240)  评论(0编辑  收藏  举报