【vue】前端下载文件自定义文件名称

589 阅读1分钟

下载文件自定义文件名称

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

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

按钮的处理

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

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

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

window.location.href = url

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)
      }
},