前端实现文件下载并且重命名

  • 调用downloadFile 方法传入两个参数即可,其他无需修改
  • 参数
    (1)src:文件路径
    (2)filename:新的文件名
   downloadFile :  async function (src, filename) {
        var url = webPath + src;//完整路径
        vm.getBlob(url).then(blob => {
            vm.saveAs(blob, filename);
        });
    },
  
    getBlob: function(url, cb){
        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);
                }
            };
            xhr.send();
        });
    },

    saveAs: function(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;
            // fix Firefox
            link.style.display = 'none';
            body.appendChild(link);
            link.click();
            body.removeChild(link);
            window.URL.revokeObjectURL(link.href);
         }
      },

你可能感兴趣的:(7-日常工作总结,js)