vue根据URL下载文件并重命名

497 阅读1分钟
介绍

最近跟后端调试接口时上传附件(包含imgxlsx)等文件类型,需要在下载到本地时展示原名称。

实现方法

首先需要在vue的methods内定义方法

downloadByBlob(row){
      let {name,cdn,type}= row; //获取数据信息
      if(type==1){     //图片
        let image = new Image(); //创建图片
        image.setAttribute('crossOrigin', 'anonymous'); //配置图片属性
        image.src = cdn
        image.onload = () => {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let ctx = canvas.getContext('2d')
          ctx.drawImage(image, 0, 0, image.width, image.height)
          canvas.toBlob((blob) => {
            let url = URL.createObjectURL(blob)
            this.download(url,name)
            // 用完释放URL对象
            URL.revokeObjectURL(url)
          })
        }
      }else if(type==4){ //xlsx文档类
          this.getBlob(cdn).then(blob=>{
              const link = document.createElement('a')
          const body = document.querySelector('body')

          link.href = window.URL.createObjectURL(blob)
          link.download = name

          link.style.display = 'none'
          body.appendChild(link)

          link.click()
          body.removeChild(link)

          window.URL.revokeObjectURL(link.href)
          })
        }
    },

//清除
  download(href, name) {
      let eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.href = href
      eleLink.click()
      eleLink.remove()
    },
//下载
 getBlob(url) {
        return new Promise((resolve) => {
          const xhr = new XMLHttpRequest()
          xhr.open('GET', url, true)
          xhr.responseType = 'blob'
          xhr.onload = () => {
            if (xhr.status === 200) {
              resolve(xhr.response)
            }
          }
          xhr.send()
        })
    }
 download(href, name) {
      let eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.href = href
      eleLink.click()
      eleLink.remove()
    }

这样我们就完成了前端下载图片文档的操作。

后话

希望对于大家的面试有所帮助,如果你还有想补充或者说明的欢迎留言评论。