天天看点

js 下载文件以及自定义下载文件名称

/**
 * 下载文件以及自定义文件名称
 */
const downFile = (url, fileName) => {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob"; // 通过文件下载url拿到对应的blob对象
  xhr.onload = () => {
    if (xhr.status === 200) {
      let link = document.createElement("a");
      let body = document.querySelector("body");
      link.href = window.URL.createObjectURL(xhr.response);
      link.download = fileName;
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    }
  };

  xhr.send();
};
downFile(
  "https://ossstaticimg.jianfuan.com/dp_test/897f9292-6cad-4465-b909-b9b1a372abb0.xlsx",
  "自定义文件名"
);      
js 下载文件以及自定义下载文件名称

继续阅读