vue3-web side file download

1. aDownload using tags

	<a
      ref="downloadRef"
      :href="downloadInfo.url"
      :download="downloadInfo.name"
      v-show="false"
    ></a>
import {
    
     ref, unref, reactive, onMounted, nextTick } from "vue"

//下载文件
const download2 = function (url: string, name: string) {
    
    
  downloadInfo.url = url;
  downloadInfo.name = name;
  
  nextTick(() => {
    
    
    unref(downloadRef).click()
  })
}

2. Use js code to download files

//下载文件
const download2 = function (url: string, name: string) {
    
    
  const link = document.createElement("a")
  // link.target = '_blank';
  link.href = url
  link.download = name
  document.body.appendChild(link);
  link.click()
  document.body.removeChild(link);
}

Note: The download file name is not the name you provided to download the attribute. After checking, it is found that when the download link of the a tag crosses the domain, the download attribute will not take effect because the browser cannot obtain the file and cannot change it.
The new feature of html5, the download attribute of a tag, only supports Google and Firefox.
The reason why modifying the file name of the download attribute of a tag in Google and Firefox browsers fails: different sources, the domain name visited and the domain name of href must be consistent.

Solution:
Use HTML5 Blob to implement file download. First download the file to the current page in the form of bobl, and then create an a tag.

// 下载文件
const download = function (aUrl: string, name: string) {
    
    
  const x = new XMLHttpRequest();
    x.open('GET', aUrl, true);
    x.responseType = 'blob';
    x.onload = function (e) {
    
    
      const url = window.URL.createObjectURL(x.response);
      const elink = document.createElement('a');
      elink.href = url;
      elink.target = '_self'; 
      // elink.setAttribute('download', name);
      elink.download = `${
      
      name}`;
      elink.style.display = 'none';
      document.body.appendChild(elink);
      setTimeout(() => {
    
    
        elink.click();
        document.body.removeChild(elink);
      }, 66);
    };
    x.send();
}

Reference link: https://blog.csdn.net/weixin_46600931/article/details/126854016

Guess you like

Origin blog.csdn.net/weixin_44801790/article/details/132869009