Download files across domains & modify file names

Introduction

The front-end generally downloads static files using commonly used atags, specifying downloadattributes, and triggering downloads.

download HTML5
This attribute instructs the browser to download the URL instead of navigating to it, so the user will be prompted to save it as a local file. If the property has a value, then this value will be used as the prepopulated filename during download save (the filename can still be changed if the user desires). This property has no restrictions on allowed values, but / and \ are converted to underscores. Most file systems limit punctuation in file names, so browsers will adjust suggested file names accordingly.

Note:
This property only applies to origin URLs.
Although the HTTP URL needs to be in the same origin, you can use blob: URL and data: URL to make it easier for users to download content generated using JavaScript (such as photos created using an online drawing web application).
If the Content-Disposition attribute in the HTTP header is assigned a file name that is different from this attribute, the HTTP header attribute takes precedence over this attribute.
If the HTTP header Content-Disposition attribute is set to inline (that is, Content-Disposition='inline'), then Firefox gives priority to the HTTP header Content-Dispositiondownload attribute.

However, this method has a drawback. In the case of cross-domain resources, downloadthe attributes will not work and the downloaded resource will be renamed. So, how to rename resources

Cross domain download

We can create a new http request for downloading static file resources.

export function downFile(url , filename) {
  axios
    .get(url, {
      responseType: 'blob'  //  注意 responseType 属性需要加上
    })
    .then(async res => {
      console.log(res);
      const data = res.data;
      const bolb = new Blob([data], { type: 'application/pdf' });  // 此处文件类型为pdf
      saveAs(bolb, filename);
    });
}

The responseTypefield tells the service to return a blob stream, which we can directly use Blobthe object to convert. After getting blobthe object, you can adownload the label

trigger download

function saveAs(blob, filename) {
  let aLink = document.createElement('a');
  let evt = document.createEvent('HTMLEvents');
  evt.initEvent('click', true, true); // initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
  aLink.download = filename;
  aLink.href = window.URL.createObjectURL(blob);
  aLink.click();
}

Create a new atag and manually trigger the download.

base64 file download

If the server performs interface encapsulation and directly returns base64a string, just convert it

function  downloadFile(content, fileName) {
      let aLink = document.createElement('a');
      let blob = base64ToBlob('data:application/pdf;base64,' + content, 'pdf');
      let evt = document.createEvent('HTMLEvents');
      evt.initEvent('click', true, true);
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    }
   function  base64ToBlob(base64) {
      return new Promise(resolve => {
        let arr = base64.split(',');
        let mime = arr[0].match(/:(.*?);/)[1];
        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        resolve(new Blob([u8arr], { type: mime }));
      });
    }
downloadFile(url, 'filename')

Guess you like

Origin blog.csdn.net/weixin_48408736/article/details/120887190