前端下载文化部几种方法(excel,zip,html,markdown、图片等等)和导出 zip 压缩包


在这里插入图片描述

1、location.href

//get请求
window.location.href = url;

2、location.href

//get请求和location.href类似
window.open(url);

3、a标签

//写法1
const download = (filename, url) => {
    let a = document.createElement('a'); 
    a.style = 'display: none'; // 创建一个隐藏的a标签
    a.download = filename;
    a.href = url;
    document.body.appendChild(a);
    a.click(); // 触发a标签的click事件
    document.body.removeChild(a);
}

4、请求后端的方式

axios({
  method: 'post',
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  url: '/robot/strategyManagement/analysisExcel',
  responseType: 'blob',
  headers: { //如果需要权限下载的话,加在这里
        Authorization: '123456'
    }
  data: JSON.stringify(params),
}).then(function(res){
   var content = res.headers['content-disposition'];
   var name = content && content.split(';')[1].split('filename=')[1];
   var fileName = decodeURIComponent(name)
   downloadFile(res.data,fileName)
})

5、文件下载的方式

downloadFile:function(data,fileName){
    // data为blob格式
    var blob = new Blob([data]);
    var downloadElement = document.createElement('a');
    var href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    downloadElement.download = fileName;
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href);
}

6、Blob和Base64

function downloadFile(res, Filename) {
  // res为接口返回数据,在请求接口的时候可进行鉴权
  if (!res) return;
  // IE及IE内核浏览器
  if ("msSaveOrOpenBlob" in navigator) {
    navigator.msSaveOrOpenBlob(res, name);
    return;
  }
  const url = URL.createObjectURL(new Blob([res]));
  //  const fileReader = new FileReader();  使用 Base64 编码生成
  // fileReader.readAsDataURL(res);
  // fileReader.onload = function() { ...此处逻辑和下面创建a标签并释放代码一致,可从fileReader.result获取href值... }
  const a = document.createElement("a");
  a.style.display = "none";
  a.href = url;
  a.download = Filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url); // 释放blob对象
}

7、下载附件方法(excel,zip,html,markdown)

/**
 * @param data 数据
 * @param fileName 文件名称
 * @param type 导出文件类型
 */
export const download = (data: Blob, fileName: string, type: string) => {
  // 创建 blob
  const blob = new Blob([data], { type: mineType[type] })
  // 创建 href 超链接,点击进行下载
  window.URL = window.URL || window.webkitURL
  const href = URL.createObjectURL(blob)
  const downA = document.createElement('a')
  downA.href = href
  downA.download = fileName
  downA.click()
  // 销毁超连接
  window.URL.revokeObjectURL(href)
}

export const mineType = {
  excel: 'application/vnd.ms-excel', // 下载 Excel
  word: 'application/msword', // 下载 Word
  zip: 'application/zip', // 下载 Zip
  html: 'text/html', // 下载 Html
  markdown: 'text/markdown', // 下载 Markdown
}

使用

download(res, '导出模板.docx', 'word')

8、封装下载函数

export const download = (res, type, filename) => {
  // 创建blob对象,解析流数据
  const blob = new Blob([res], {
    // 设置返回的文件类型
    // type: 'application/pdf;charset=UTF-8' 表示下载文档为pdf,如果是word则设置为msword,excel为excel
    type: type
  })
  // 这里就是创建一个a标签,等下用来模拟点击事件
  const a = document.createElement('a')
  // 兼容webkix浏览器,处理webkit浏览器中href自动添加blob前缀,默认在浏览器打开而不是下载
  const URL = window.URL || window.webkitURL
  // 根据解析后的blob对象创建URL 对象
  const herf = URL.createObjectURL(blob)
  // 下载链接
  a.href = herf
  // 下载文件名,如果后端没有返回,可以自己写a.download = '文件.pdf'
  a.download = filename
  document.body.appendChild(a)
  // 点击a标签,进行下载 
  a.click()
  // 收尾工作,在内存中移除URL 对象
  document.body.removeChild(a)
  window.URL.revokeObjectURL(herf)
}

9、导出 zip 压缩包相关方法(流方式)

后端的设置 Content-Type: application/octet-stream(下载用的流)

 // 下载zip方法
    //zip格式文件下载
    zipdwonUpload(data) {
      console.log("干部任免表传递的数据", data);
      let ids = data.ids;
      console.log("ids集合数据", ids);
      // 导出干部任免表接口
      this.$axios
        .post(`personnel/exportAppointmentAndDismissal`, ids, {
          responseType: "blob",
        })
        .then((res) => {
          // res
          let blob = res;
          let that = this;
          //通过FileReader读取数据,是一种异步文件读取机制
          let reader = new FileReader();
          //以下这两种方式我都可以解析出来,因为Blob对象的数据可以按文本或二进制的格式进行读取
          // reader.readAsBinaryString(blob, 'utf8');
          reader.readAsText(blob, "utf8");
          // eadAsText(file, encoding);以纯文本的方式读取,读取到的文本保存在result属性中。第二个参数代表编码格式

          reader.onload = function (result) {
            //onload在成功加载后就会触发
            console.log("result信息", result);
            console.log(
              "isJson判断是否为json格式",
              that.isJSON(result.target.result)
            );
            if (that.isJSON(result.target.result)) {
              that.$message.warning(JSON.parse(result.target.result).msg);
              // loading效果
              // that.loadingBut = false;
            } else {
              console.log("下载zip数据", res);
              // that.downloadFile(res);
            }
          };
        })
        .catch((error) => {
          console.log(error);
          // 打印错误
        })
        .finally(() => {
          // 导出按钮loading效果
          this.isDownloadingFile = false;
        });
    },

使用导出 zip

    // 导出zip
    downloadFile(res) {
      // res 下载转blob二进制或文本数据
      let blob = new Blob([res], { type: "application/zip" });
      console.log("导出的blob", blob);
      if (window.navigator.msSaveOrOpenBlob) {
        // msSaveOrOpenBlob 提供保存和打开按钮
        navigator.msSaveOrOpenBlob(blob, "xxx.zip");
        // navigator.msSaveOrOpenBlob(blob, "xxx.zip");
        return;
      }
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement("a"); // 创建a标签
      link.href = url;
      link.download = `干部任免压缩包`; // 重命名文件
      link.click();
      URL.revokeObjectURL(url); // 释放内存
      // this.loadingBut = false; //loading效果
    },

总结

如果这篇【文章】有帮助到你💖,希望可以给我点个赞👍,创作不易,如果有对前端或者对python感兴趣的朋友,请多多关注💖💖💖,咱们一起探讨和努力!!!
👨‍🔧 个人主页 : 前端初见

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端初见

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值