前端实现文件下载

100 阅读1分钟

一、直接使用a标签

// url下载地址;
// fileName文件名,只有 Firefox 和 Chrome 支持 download 属性
<a href="url" download="fileName">下载文件</a>

二、js方式使用a标签

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="renderer" content="webkit" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
    />
  </head>

  <body>
    <body>
      <div onclick="downFile()">下载文件</div>
    </body>
    <script>
      function downFile() {
        const a = document.createElement("a");
        a.setAttribute("download", fileName);
        a.setAttribute("href", url);
        a.click();
      }
    </script>
  </body>
</html>

三、使用window.open(url)

// 有局限性,对于图片只是打开一个新页签,建议使用a标签
window.open(url);

四、示例 axios请求

  • 数据流形式
axios.get("你的url", {
  responseType: "blob",
}).then((res) => {
  const blob = new Blob([res.data]);
  letlink = document.createElement("a"); //创建a标签
  link.download = "你的fileName"; //a标签添加属性
  link.style.display = "none";
  link.href = URL.createObjectURL(blob);
  document.body.appendChild(link);
  link.click(); //执行下载
  URL.revokeObjectURL(link.href); //释放url
  document.body.removeChild(link); //释放标签
});
  • url形式 
axios.get("你的url").then((res) => {
  letlink = document.createElement("a"); //创建a标签
  link.download = "你的fileName"; //a标签添加属性
  link.style.display = "none";
  link.href = res.url; // 下载全路径
  document.body.appendChild(link);
  link.click(); //执行下载
  URL.revokeObjectURL(link.href); //释放url
  document.body.removeChild(link); //释放标签
});

优缺点:

  • 数据流的形式,可以在axios(onDownloadProgress)中获取进度,缺点是下载过程中不能做其他操作,完全是等待状态,刷新页面就没了。
  • url形式,首先是创建一个链接,然后就是浏览器的默认行为,通常是在浏览器下面多一个下载文件,这时候完全可以做其他的事情。