前端实现下载excel、img、zip....方法有两种

    1. 直接调接口进行下载 后端进行处理                        多GET请求

    2. 调取接口返回对应的文件流,前端进行处理           多POST请求

axios.get("/api?id=2", {
          responseType: 'blob'  // zip文件流需要添加,不然文件无法打开
        }).then(res => {
           let Res = new ResDatas({
            res,
          }).init();
          let contentType = res.headers['content-type'];
          let contentDisposition = res.headers['content-disposition'];
          if(contentType.indexOf('application/json') != -1) {
            this.$message({
              message: Res,
              type: "warning"
            });
          } else {
            contentDisposition = contentDisposition.split(";")[1];
            let filename = contentDisposition.split("=")[1];
            let filenameStr = window.decodeURI(filename.split(",")[0],"utf-8"); // 下载的文件名称
            _customDownLoadZipGet(res.data, filenameStr);
          }
        })

/**
 * @name:
 * @param {type}
 * @return:
 * @description: (前端)文件流转换
 */
 export const _customDownLoadZipGet = (data, fileName) => {
  const blob = new Blob([data]);
  const downloadElement = document.createElement("a");
  const href = window.URL.createObjectURL(blob);
  //后台再header中传文件名
  downloadElement.href = href;
  downloadElement.download = fileName;
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href); // 释放掉blob对象
};

Logo

前往低代码交流专区

更多推荐