# 下载文件常用方式

# 根据图片地址下载图片

/**
 * @imgsrc 图片地址
 * @name 图片名
 */
const downloadIamge = (imgsrc, name) => {
  let image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function () {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
    let a = document.createElement("a"); // 生成一个a元素
    let event = new MouseEvent("click"); // 创建一个单击事件
    a.download = name || "photo"; // 设置图片名称
    a.href = url; // 将生成的URL设置为a.href属性
    a.dispatchEvent(event); // 触发a的单击事件
  };
  image.src = imgsrc;
};

# 下载视频

window.open(url,"_self")

# 下载流 blob

const downLoadBlob = (data,filename) => {
    let blob = new Blob([data]);
    let a = document.createElement("a");
    let href = window.URL.createObjectURL(blob);
    a.href = herf;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(objectURL);
}

# 获取url里面文件名

const getFileNameFromURL = (url) => {
  let arr = url.split("/");
  let len = arr.length;
  let file = arr
    .slice(len - 1, len)
    .toString()
    .split(".");
  return file.slice(0, 1).toString();
};

# 获取文件扩展名

const getFileExtension = (filename) => {
  return filename.substring(filename.lastIndexOf(".") + 1);
};
// getFileExtension(example.zip)  -> zip
Last Updated: 10/23/2022, 2:26:04 AM