当前位置:网站首页>Download the OSS file and modify the file name

Download the OSS file and modify the file name

2022-06-23 07:28:00 But I love you

oss The files on the can be created dynamically directly a Tag to download , But the downloaded file name is oss Given , Not converted to blob Type a.download It's invalid

First convert the file into a file stream , Then dynamically create a label , change a.download Property to change the file name

1. Download the file as a stream file


  function getBlob(url) {
     // url: It's the file in oss Address on 
    return new Promise(resolve => {
    
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";//  The request type is blob type 
      xhr.crossOrigin = "*"; //  Solving cross domain problems 
      xhr.onload = () => {
    
        if (xhr.status === 200) {
    
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

2. Download the file and rename it

function saveAs(blob, filename) {
    
    if (window.navigator.msSaveOrOpenBlob) {
    
      navigator.msSaveBlob(blob, filename);
    } else {
    
      const link = document.createElement("a");
      const body = document.querySelector("body");
      link.href = window.URL.createObjectURL(blob);
      link.download = filename; // Change file name 
      link.style.display = "none";
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    }
  }

3. Use

  getBlob(url).then(res =>{
     //url: The file in oss Address on 
       saveAs(res,filename) // filename: file name , Customizable 
  })
原网站

版权声明
本文为[But I love you]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230504373259.html