search
HomeWeb Front-endJS TutorialUse Blod to make ajax progress bar download

This time I will bring you the use of Blod to make ajax progress bar downloads. What are the precautions for using Blod to make ajax progress bar downloads? The following is a practical case, let's take a look.

Ordinary browser download

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

<a>点击下载</a>
//或者
<iframe></iframe>
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 is required to provide a sufficient package to encapsulate this The type of binary file, this is blod. Therefore, set the response type and the value of responseType to "blod":

var xhr =new XMLHttpRequest();
xhr.open(option.type ? option.type.toUpperCase() : 'GET', url, true);
xhr.responseType = 'blob';
Requires the value of the responseType field of the XMLHttpRequest object to be 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 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? <p style="text-align: left;"></p><p style="text-align: left;">Save the blob object on the hard disk<strong></strong></p>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 <p style="text-align: left;">ie browser<a href="http://www.php.cn/browsers/browsers-explorer.html" target="_blank">, it has its own set of Blob object processing strategies, which are the two navigator methods msSaveOrOpenBlob and msSaveBlob. </a></p><pre class="brush:php;toolbar:false">//ie的下载
if (window.navigator.msSaveOrOpenBlob) {
  navigator.msSaveBlob(blob, fileName);
} else {
  //非ie的下载
  var link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
  window.URL.revokeObjectURL(link.href);
}

Progress bar and download cancellation

Then there are 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 optimizationAnd same-origin policy

Ajax downloads, like long connections, will occupy more bandwidth than ordinary requests, especially downloads that require bandwidth The occupation is even more serious. Therefore, other ajax requests may be blocked during the download process, so it is recommended that the resources downloaded by ajax and other requested resources use different domain names, but this will bring new problems - 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 methods 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 is required. 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 would like to offer you an ajax download demo from the author: ajaxDownloadDemo_jb51.rar

##I believe that you have mastered the method after reading the case in this article. Please come for more exciting information. Pay attention to other related articles on php Chinese website!

Recommended reading:

How to communicate data between C and View

What are the front-end and back-end types? ajax interaction method

The above is the detailed content of Use Blod to make ajax progress bar download. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft