常见文件下载相关的方法

// 导出操作相关的方法
// 数据导出功能
async function downloadData(httpUrl, params, fileName, type = "application/vnd.ms-excel") {
  console.log("数据导出中……");
  const data = await httpUrl(params);
  const fileTypeList = ["application/vnd.ms-excel", "application/force-download", "application/octet-stream"];
  return new Promise((resolve, reject) => {
    if (data && fileTypeList.indexOf(data.type) > -1) {
      const blob = new Blob([data], {
        type,
      });
      if (!!window.ActiveXObject || "ActiveXObject" in window) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        let link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", fileName);
        link.click();
        link = null;
      }
      resolve();
    } else {
      console.log("暂无可以导出的数据");
      reject(new Error("暂无可以导出的数据!"));
    }
  });
}

// 根据url下载图片
const downImage = (imgsrc) => {
  let image = new Image();
  image.src = `${imgsrc}?v=${Math.random()}`; // 处理缓存
  image.crossOrigin = "*"; // 支持跨域图片
  image.onload = function () {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, image.width, image.height);
    let base64 = canvas.toDataURL("image/png");
    let tmpa = document.createElement("a");
    tmpa.download = base64;
    tmpa.href = base64; // 绑定a标签
    tmpa.target = base64; // 绑定a标签
    tmpa.click(); // 模拟点击实现下载
  };
};
/**
 * 根据图片的url转换对应的base64值
 * @param { String } imageUrl 如:http://xxxx/xxx.png
 * @returns base64取值
 * @Note 注意:可能涉及图片访问有跨域问题,让后台解决即可。
 */
const urlToBase64 = (imageUrl) => new Promise((resolve, reject) => {
  let canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  let img = new Image();
  img.crossOrigin = "Anonymous"; // 解决Canvas.toDataURL 图片跨域问题
  img.src = imageUrl;
  img.onload = function () {
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0, img.width, img.height); // 参数可自定义
    const dataURL = canvas.toDataURL("image/jpeg", 1); // 获取Base64编码
    resolve(dataURL);
    canvas = null; // 清除canvas元素
    img = null; // 清除img元素
  };
  img.onerror = function () {
    reject(new Error(`Could not load image at ${imageUrl}`));
  };
});

// 实现文件下载并重命名。主要解决,不同源情况的下载
/**
 * 获取 blob
 * url 目标文件地址
 */
const getBlob = (url) =>
  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();
  });

/**
 * 保存 blob
 * filename 想要保存的文件名称
 */
const saveAs = (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);
  }
};

const downloadFile = (url, filename) => {
  getBlob(url).then((blob) => {
    saveAs(blob, filename);
  });
};
export { downloadData, urlToBase64, downImage, downloadFile };

 

posted on 2024-08-09 17:27  紫藤萝yu  阅读(9)  评论(0编辑  收藏  举报