目录

js下载文件

Admin8/2/2022620 阅读

利用Blob对象

js 复制代码
/**
 * 下载文件
 * @param {String} path - 下载地址/下载请求地址。
 * @param {String} name - 下载文件的名字(考虑到兼容性问题,最好加上后缀名)
 */
import { ElMessage } from \"element-plus\";
export default {
  downloadFile(path, name) {
    const xhr = new XMLHttpRequest();
    xhr.open(\"get\", path);
    xhr.responseType = \"blob\";
    xhr.send();
    xhr.onload = function () {
      if (this.status === 200 || this.status === 304) {
        const url = URL.createObjectURL(this.response);
        const a = document.createElement(\"a\");
        a.style.display = \"none\";
        a.href = url;
        a.download = name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        ElMessage.success(\"下载文件成功\");
      } else {
        ElMessage.error(\"下载文件失败\");
      }
    };
  },
};

利用base64

js 复制代码
/**
 * 下载文件
 * @param {String} path - 下载地址/下载请求地址。
 * @param {String} name - 下载文件的名字(考虑到兼容性问题,最好加上后缀名)
 */
downloadFile (path, name) {
    const xhr = new XMLHttpRequest();
    xhr.open('get', path);
    xhr.responseType = 'blob';
    xhr.send();
    xhr.onload = function () {
        if (this.status === 200 || this.status === 304) {
            const fileReader = new FileReader();
            fileReader.readAsDataURL(this.response);
            fileReader.onload = function () {
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = this.result;
                a.download = name;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            };
        }
    };
}

评论

共 0 条
后参与评论
共 104 篇文章 感谢支持

RSS ·关于

© 2026 我的博客