How to implement download function in javascript

藏色散人
Release: 2023-02-10 09:57:09
Original
3769 people have browsed it

How to implement the download function in javascript: 1. Download through the a tag; 2. Download through the "window.open" method; 3. Download through the "location.href" method; 4. Through file transfer The blob object implements the download function.

How to implement download function in javascript

The operating environment of this tutorial: Windows 10 system, javascript version 1.8.5, Dell G3 computer.

How to implement the download function in javascript?

js implements file download function

1. a tag download

<body>
<button onClick="download()">a标签下载</button>
<script>
function download(url = &#39;http:www.xxx.com/download?name=file.pdf&#39;, fileName = &#39;未知文件&#39;) {
      const a = document.createElement(&#39;a&#39;);
      a.style.display = &#39;none&#39;;
      a.setAttribute(&#39;target&#39;, &#39;_blank&#39;);
      /*
       * download的属性是HTML5新增的属性
       * href属性的地址必须是非跨域的地址,如果引用的是第三方的网站或者说是前后端分离的项目(调用后台的接口),这时download就会不起作用。
       * 此时,如果是下载浏览器无法解析的文件,例如.exe,.xlsx..那么浏览器会自动下载,但是如果使用浏览器可以解析的文件,比如.txt,.png,.pdf....浏览器就会采取预览模式
       * 所以,对于.txt,.png,.pdf等的预览功能我们就可以直接不设置download属性(前提是后端响应头的Content-Type: application/octet-stream,如果为application/pdf浏览器则会判断文件为 pdf ,自动执行预览的策略)
       */
      fileName && a.setAttribute(&#39;download&#39;, fileName);
      a.href = url;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
</script>
</body>
Copy after login

Advantages:

  • You can directly download txt, png, pdf, exe, xlsx and other types of files

Disadvantages:

  • a tag can only do get requests , so the url has a length limit

  • Unable to obtain download progress

  • Cross-domain restrictions

  • Unable Carrying the token in the header for authentication operation

  • Unable to determine whether the interface is successful

  • IE compatibility issues

2. Download window.open

<body>
  <button onclick="download(&#39;http://www.xxx.com/download?name=file.pdf&#39;)">window.open下载</button>
  <script>
    function download(url) {
      window.open(url, &#39;_self&#39;);
      /**
       *  _blank:在新窗口显示目标网页
       *  _self:在当前窗口显示目标网页
       *  _top:框架网页中在上部窗口中显示目标网页
      /**
    }
  </script>
</body>
Copy after login

Advantages:

  • Simple and convenient

Disadvantages:

  • There will be a URL length limit problem

  • You need to pay attention to the url encoding problem

  • Unable to get the download progress

  • Unable to carry token in header for authentication operation

  • Unable to determine whether the interface is successful

  • Unable to directly Download file types that can be directly previewed by the browser (txt, png, pdf will be previewed directly)

3. Download location.href

<body>
  <button onclick="download(&#39;http://www.xxx.com/download?name=file.pdf&#39;)">location.href下载
  </button>
  <script>
    function download(url) {
      window.location.href = url;
    }
  </script>
</body>
Copy after login

Advantages

  • Simple, convenient and direct

  • Can download large files (G or above)

Disadvantages

  • There will be a URL length limit problem

  • You need to pay attention to the url encoding problem

  • Unable to get the download progress

  • Cannot carry token in header for authentication operation

  • Cannot directly download file types that can be previewed directly by the browser (txt, png, pdf will be previewed directly)

  • Unable to determine whether the interface returns successfully

3. File transfer blob object download

 <button onclick="download()">文件流转blob对象下载</button>
 <script>
 download() {
 axios({
 url: &#39;http://www.xxx.com/download&#39;,
 method: &#39;get&#39;,
 responseType: &#39;blob&#39;,
 }).then(res => {
 const fileName = res.headers.content-disposition.split(&#39;;&#39;)[1].split(&#39;filename=&#39;)[1];
 const filestream = res.data;  // 返回的文件流
 // {type: &#39;application/vnd.ms-excel&#39;}指定对应文件类型为.XLS (.XLS的缩写就为application/vnd.ms-excel)
 const blob = new Blob([filestream], {type: &#39;application/vnd.ms-excel&#39;});
 const a = document.createElement(&#39;a&#39;);
 const href = window.URL.createObjectURL(blob); // 创建下载连接
    a.href = href;
    a.download = decodeURL(fileName );
    document.body.appendChild(a);
        a.click();
        document.body.removeChild(a); // 下载完移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
 })
 }
 </script>
Copy after login

Advantages:

  • You can download txt, png, pdf and other types of files

  • You can carry token in the header for authentication operation

  • You can get the file download progress

  • You can judge whether the interface returns successfully

Disadvantages:

  • Compatibility issues, not available below IE10, pay attention to Safari browser, the official website states that Safari has a serious issue with blobs that are of the type application/octet-stream

  • Return the backend It will be downloaded only after all the file streams have been obtained

Recommended learning: "JavaScript Video Tutorial"

The above is the detailed content of How to implement download function in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template