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

亚连
Release: 2018-05-22 16:46:56
Original
1948 people have browsed it

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!

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