侧边栏壁纸
博主头像
MicroMatrix博主等级

曲则全,枉则直,洼则盈,敝则新,少则得,多则惑。是以圣人抱一为天下式。不自见,故明;不自是,故彰;不自伐,故有功;不自矜,故长。夫唯不争,故天下莫能与之争。古之所谓“曲则全”者,岂虚言哉!诚全而归之。

  • 累计撰写 80 篇文章
  • 累计创建 21 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

前端实现文件下载

蜗牛
2022-05-28 / 0 评论 / 0 点赞 / 7 阅读 / 3539 字 / 正在检测是否收录...

前言

前端开发过程中,总会遇到点击链接下载。这个时候可以借助2种方法解决。一种是用a标签的download,第二种是按钮点击之后调用接口来下载。2种方法最好确定文件没有跨域现象。

a标签download

//点击按钮或者什么,生成a链接,然后将文件地址放在上面
downloadFile(url, fileName) {
    let aLink = document.createElement("a");
    document.body.appendChild(aLink);
    aLink.setAttribute("href", url);
    aLink.setAttribute("download", fileName);
    aLink.click();
    document.body.removeChild(aLink);
},

ajax或者fetch访问下载

/**
* @description:
* @param {*} url 目标文件地址
* @param {*} filename 目标文件名
* @return {*}
* @Date: 2021-02-26 10:05:51
* @Author: David
*/
downloadFile(url, filename) {
    this.getBlob(url, function(blob) {
        this.saveAs(blob, filename);
    });
},
getBlob(url, cb) {
 let xhr = new XMLHttpRequest();
 xhr.open("GET", url, true);
 xhr.responseType = "blob";
 xhr.onload = function() {
 if (xhr.status === 200) {
  cb(xhr.response);
 }
};
xhr.send();
}

/**
* @description: 保存
* @param {*} blob
* @param {*} filename 想要保存的文件名称
* @return {*}
* @Date: 2021-02-26 10:05:32
* @Author: David
*/
saveAs(blob, filename) {
 if (window.navigator.msSaveOrOpenBlob) {
  navigator.msSaveBlob(blob, filename);
 } else {
  var link = document.createElement("a");
  var 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);
 }
}
0

评论区