Home Web Front-end JS Tutorial Ajax progress bar download implementation sample code based on Blod

Ajax progress bar download implementation sample code based on Blod

May 22, 2018 pm 04:46 PM
ajax download

This article mainly introduces the sample code for ajax progress bar download implementation based on Blod. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Ordinary browser download

In web development, if you want to implement the download function, you often use a newly opened web page Or use iframe. The implementation is actually very simple:

<a target="_blank" href="download.zip" rel="external nofollow" >点击下载</a>
//或者
<iframe style="display:none" src="download.zip"></iframe>
Copy after login

After the user clicks the a tag to pop up a new tab, or after opening the iframe, the browser will accept a download response and download the attachment. In fact, the so-called attachment download means that after the browser reads the header of the response message, the browser generates a download prompt box and will continue to download the file after the user confirms. A file is actually a stream. The so-called stream is a transmission process. The browser will automatically manage this transmission process and automatically generate a progress bar, stop download button, continue button, cancel download button, display update downloaded byte number button, etc. . The browser does this for us automatically, and the whole process is not under our control.

ajax download

The browser’s support for downloading can basically meet our needs. We will explore other options in general scenarios. The download method makes little sense. However, there are still some scenarios that browser downloads cannot satisfy. For example, our web application is required to monitor the download progress, or trigger a specific event after the download is completed, or the web application can automatically cancel the download process, or use a worker to create a background running Download and more. For the above situations, we can use ajax download based on Blod object.

Ajax download attachments are the same as ajax upload attachments, and the browser needs to support ajax2.0. In fact, the so-called download is no different from an ordinary ajax request. They are all requests for a URL address. However, downloads are generally binary files, not text objects or json objects. JavaScript needs to provide a type that can encapsulate the binary file. This It’s blood. Therefore, you need to set the response type and the value of responseType to "blod":

var xhr =new XMLHttpRequest();
xhr.open(option.type ? option.type.toUpperCase() : &#39;GET&#39;, url, true);
xhr.responseType = &#39;blob&#39;;
Copy after login

It is required that the value of the responseType field of the XMLHttpRequest object is blob. So what is the blod object?

blod object

MDN describes it as:

Blob object is a file-like object containing read-only raw data. The data in a Blob object does not have to be in its native form in JavaScript. The File interface is based on Blob, inherits the functions of Blob, and extends support for local files on the user's computer. Through the Blob object we can encapsulate a binary stream into an object.

If you know the file-related API of HTML5, you should be familiar with the blod object. Blod can encapsulate a byte stream into a file. If the responseType value of the XMLHttpRequest object is blob, we can treat the response body as a blob object.

xhr.onload = function () {
  //对于重定向的文件不予理会
  if (this.status >= 200 && this.status < 300) {
    var blob = new Blob([this.response], {type: this.response.type});
  }
}
Copy after login

Use ajax to download the file, then save the file as a blob object and cache it in the browser. So how do you let users save files to their hard drive?

Save the blob object on the hard disk

We can imitate the browser download, generate an a tag or iframe, and then generate a url, so that we return to the browser After downloading, the browser will automatically generate a window to save the attachment. The URL can be obtained using the URL.createObjectURL(blob) method. URL.createObjectURL supports Blob objects and File objects, and can generate a virtual URL so that the current user can access these objects, including downloads, of course. Different from downloading directly from the server, the download here is internal to the client and does not use network io, so the download is almost instantaneous. However, after generating the url, it must be released, otherwise the blob resource will not be garbage collected. You can use URL.revokeObjectURL to release the url and release the blob resource. For IE browser, it has its own set of Blob object processing strategies, which are two navigator methods: msSaveOrOpenBlob and msSaveBlob.

//ie的下载
if (window.navigator.msSaveOrOpenBlob) {
  navigator.msSaveBlob(blob, fileName);
} else {
  //非ie的下载
  var link = document.createElement(&#39;a&#39;);
  link.href = window.URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
  window.URL.revokeObjectURL(link.href);
}
Copy after login

Progress bar and download cancellation

Then there is the progress bar and download cancellation function. In fact, the XMLHttpRequest object has a progress event, but we usually make ajax requests Ignore him. After all, general requests are instantaneous and there is no need to set a progress bar for them. But ajax download is different. Downloading attachments takes time, so it is necessary to develop a progress bar for it. By listening to the progress event, we can get the download progress.

Use the abort function of the XMLHttpRequest object to cancel the download. In addition, the load event can monitor the download completion, and the error event can monitor the download failure. In short, the events and methods of ajax download and an ordinary ajax request are exactly the same.

Performance optimization and same-origin policy

Ajax downloads, like long connections, will occupy more bandwidth than ordinary requests, especially downloads, which occupy more bandwidth. Therefore, other ajax requests may be blocked during the download process, so it is recommended that the resources downloaded by ajax use different domain names from other requested resources, but this will bring about a new problem - the same origin policy issue.

The same origin policy is the cornerstone of browser security. Without a same origin policy, any website can launch a CSRF attack. If it cannot be guaranteed that the URL of the downloaded resource has the same origin as the URL of the current page, the same origin policy will be triggered and the download will fail. Therefore, Ajax cross-domain processing is required. Compared with the download method of iframe and new tab (in fact, iframe also has a same-origin policy, which requires that the page inside the iframe and the parent page cannot access each other's content, but the download function does not involve this kind of access to each other's content, so iframe download is Not affected by the same origin policy), ajax download is still ajax in nature, so it will be affected by the browser's same origin policy. Therefore, if you download an attachment from a non-original source, the server where the attachment is located needs to support cors. If the server needs to access cookies, the withCredentials of the XMLHttpRequest object must be set to true.

At the same time, due to the same-origin policy, we cannot use ajax to download third-party resources, because the usual download services do not do cors processing, such as iframe downloads or new tab downloads. The method is not affected by the same-origin policy, so there is no need to do cors processing. This greatly limits the applicability of ajax downloading.

Summary:

Finally, let’s summarize the usage scenarios of ajax download:

1. Scenarios where the download progress needs to be monitored, such as It was found that the user's download progress was too slow and other solutions were proactively provided.

2. A specific event needs to be triggered after the download is completed, such as a desktop prompt Notification popping up.

3. A background download needs to be provided. For example, we can secretly download the attachment after the user opens the web page and cache it, and then save it locally when the user really wants to download the attachment. We can even use workers to create a background thread to ensure that the download process does not affect the normal rendering of the page.

4. It needs to be downloaded and not saved in the hard disk, but the webapp processes the attachment directly. For example, pdf.js uses ajax to download.

Finally, I present the author’s ajax download demo: ajaxDownloadDemo_jb51.rar

##The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. .

Related articles:

Methods for mutual conversion between simple entity classes and xml files

Using Ajax to partially update Razor pages (graphic tutorial )

AjaxFileUpload Struts2 implements multi-file upload function

The above is the detailed content of Ajax progress bar download implementation sample code based on Blod. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 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 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.

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

Where to download files from Quark Network Disk_How to download Quark Network Disk to local area and share Where to download files from Quark Network Disk_How to download Quark Network Disk to local area and share Mar 21, 2024 pm 03:57 PM

As a convenient and practical network disk tool, Quark can help users easily obtain their favorite resources. What if you want to download a file locally? Let the editor tell you now, let’s learn it together! How to download Quark Network Disk to local sharing method 1. First open the Quark software, enter the homepage, and click the [Cloud Icon] on the lower right; 2. Then on the Quark Network Disk page, we click the [Document] function; 3. Then go to the document page, select the file you want to download, and click the [three-dot icon]; 4. After the final click, we click [Download] in the pop-up dialog box;

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to download and save Douyin videos How to download and save Douyin videos Mar 25, 2024 pm 09:46 PM

How to download and save Douyin videos? You can download and save videos in Douyin short video APP. Most users don’t know how to download and save Douyin videos. Next is the diagram of how to download and save Douyin videos brought by the editor. Text tutorial, interested users come and take a look! Tutorial on how to use Douyin: How to download and save Douyin videos 1. First open the Douyin short video APP, enter the main page and click the [Share] button on the right; 2. After that, the multi-function bar will expand below, slide to the right to find [ Save local] icon; 3. Then you need to wait for the download, and then the [Saved, please go to the album to view] border will appear; 4. Finally jump to the album page, and you can see that the video you just downloaded has been saved.

See all articles