vue implementation file download

principle

<a href="url" download="文件名.后缀名">
复制代码

The actual usage scenarios

Principle above for open resources download, use the http request without authentication. In actual use, a label the url directly header is too much trouble and unsafe, and the package generally look (header in need some specific settings) from the development of norms api, into a unified document.

Solution: download and api responseType set to blob (!!! important), js create a label after obtaining a file to blob form, url and downlaod settings and trigger the last release and remove the url resources to create a tag

api:
downloadFile (url) => {
  axios.get(url, {
    params: {

    },
    headers: {

    },
    // 重要
    responseType: 'blob'
  })
}


html: 
<button @click="download">下载</button>


js: 
  function downlaod (param){
    api.downloadFile(param).then(data => {
      if (!data) {
        this.$Message.error('下载内容为空')
        return
      }
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', etcdCluster + '.zip')
        
      document.body.appendChild(link)
      link.click()
      //释放URL对象所占资源
      window.URL.revokeObjectURL(url)
      //用完即删
      document.body.removeChild(link)
    }).catch(err => {
      console.log('err: ', err)
    })
  } 
    
复制代码

MDN Links

developer.mozilla.org/zh-CN/docs/… developer.mozilla.org/zh-CN/docs/…

Reproduced in: https: //juejin.im/post/5d078a67f265da1b6f43759a

Guess you like

Origin blog.csdn.net/weixin_33816821/article/details/93177512