JS下载附件重命名

使用场景

附件url为外部系统,下载时需要用内部系统的业务号重新命名

function 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);
      }else if(xhr.status === 404) {
        alert("附件地址已失效");
      }else{
        alert("附件下载异常,请联系管理员");
      }
    };
    xhr.send();
   });
}

function saveAs(blob, filename) {
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.click();
};   
     
function changeName(url,customID) {
    let fileName = '';
    if( customID == '' || customID== undefined ){
      let arr = url.split('/');
      fileName = arr[arr.length-1];
    }else{
      fileName = customID+ '.json';
    }
    getBlob(url).then(blob => {
       saveAs(blob,fileName);
    })
};

你可能感兴趣的:(javascript,开发语言)