Home Web Front-end Front-end Q&A How to implement download function in javascript

How to implement download function in javascript

Feb 10, 2023 am 09:18 AM
javascript download

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use magnet links How to use magnet links Feb 18, 2024 am 10:02 AM

Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to download episodes of Hongguo short drama How to download episodes of Hongguo short drama Mar 11, 2024 pm 09:16 PM

Hongguo Short Play is not only a platform for watching short plays, but also a treasure trove of rich content, including novels and other exciting content. This is undoubtedly a huge surprise for many users who love reading. However, many users still don’t know how to download and watch these novels in Hongguo Short Play. In the following, the editor of this website will provide you with detailed downloading steps. I hope it can help everyone in need. Partners. How to download and watch the Hongguo short play? The answer: [Hongguo short play] - [Audio book] - [Article] - [Download]. Specific steps: 1. First open the Hongguo Short Drama software, enter the homepage and click the [Listen to Books] button at the top of the page; 2. Then on the novel page we can see a lot of article content, here

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

How to download links starting with 115://? Download method introduction How to download links starting with 115://? Download method introduction Mar 14, 2024 am 11:58 AM

Recently, many users have been asking the editor, how to download links starting with 115://? If you want to download links starting with 115://, you need to use the 115 browser. After you download the 115 browser, let's take a look at the download tutorial compiled by the editor below. Introduction to how to download links starting with 115:// 1. Log in to 115.com, download and install the 115 browser. 2. Enter: chrome://extensions/ in the 115 browser address bar, enter the extension center, search for Tampermonkey, and install the corresponding plug-in. 3. Enter in the address bar of 115 browser: Grease Monkey Script: https://greasyfork.org/en/

How to download files from 123 cloud disk How to download files from 123 cloud disk Feb 23, 2024 pm 08:58 PM

123 cloud disk can download many files, so how to download files specifically? Users can select the file they want to download and click to download, or right-click the file and select download. This introduction to the method of downloading files from 123 cloud disk can tell you how to download it specifically. Friends who don’t know much about it should hurry up and take a look! How to download files from 123 cloud disk 1. First open the software, click on the software that needs to be downloaded, and then there will be a download button on it. 2. Or right-click the software and you can see the download button in the list. 3. There will be a download window, select the location to download. 4. After selecting, click Download to download these files.

How to download videos from a video account 'Must-see: A simple way to save videos from a video account' How to download videos from a video account 'Must-see: A simple way to save videos from a video account' Feb 06, 2024 pm 06:42 PM

Now more and more people are starting to play video accounts. Video accounts are also a short video platform where they can share their daily life and make money through video accounts. Recently, I saw some friends asking why the videos from the WeChat video account were not downloaded. Yang Shuaikang went to try it, and there was indeed no download button, so he could only extract the video through other means. Today Yang Shuaikang will share with you a stupid Method, come and take a look. How to extract videos from WeChat video accounts 1. Open our computer version of WeChat and find [Video Account] on the left; 2. Find the video you want to download through search; 3. Finally, use the screen recording tool to adjust the size of the recorded video. Just record and edit it at the end. PS: 1. This method can only be recorded on the computer version, not on the mobile phone.

Introduction to how to download and install the superpeople game Introduction to how to download and install the superpeople game Mar 30, 2024 pm 04:01 PM

The superpeople game can be downloaded through the steam client. The size of this game is about 28G. It usually takes one and a half hours to download and install. Here is a specific download and installation tutorial for you! New method to apply for global closed testing 1) Search for "SUPERPEOPLE" in the Steam store (steam client download) 2) Click "Request access to SUPERPEOPLE closed testing" at the bottom of the "SUPERPEOPLE" store page 3) After clicking the request access button, The "SUPERPEOPLECBT" game can be confirmed in the Steam library 4) Click the install button in "SUPERPEOPLECBT" and download

How to download Quark network disk to local? How to save files downloaded from Quark Network Disk back to the local computer How to download Quark network disk to local? How to save files downloaded from Quark Network Disk back to the local computer Mar 13, 2024 pm 08:31 PM

Many users need to download files when using Quark Network Disk, but we want to save them locally, so how to set this up? Let this site introduce to users in detail how to save files downloaded from Quark Network Disk back to the local computer. How to save files downloaded from Quark network disk back to your local computer 1. Open Quark, log in to your account, and click the list icon. 2. After clicking the icon, select the network disk. 3. After entering Quark Network Disk, click My Files. 4. After entering My Files, select the file you want to download and click the three-dot icon. 5. Check the file you want to download and click Download.

See all articles