Example code for downloading the ajax progress bar based on Blod: blodajajax
Download from a normal browser
In web development, download functions are usually implemented through a new web page or iframe. The implementation is actually very simple:
<A target = "_ blank" href = "download.zip" rel = "external nofollow"> click to download </a> // or <iframe style = "display: none "src =" download.zip "> </iframe>
After you click the tab to bring up a new tab, or open iframe, the browser will receive 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 to continue downloading the file after the user confirms. A file is actually a stream. A stream is a transmission process. The browser automatically manages the transmission process, the progress bar, stop Download button, continue button, cancel download, and display the updated download byte button. These are all automatically performed by the browser for us, and the whole process is not under our control.
Ajax download
The browser's support for downloads basically satisfies our needs. It is of little significance to explore other download methods in general scenarios. However, in some scenarios, browser downloading does not meet the requirements. For example, we require our web applications to monitor the download progress or trigger a specific event after the download is complete, or the web application can automatically cancel the download process, or use worker to create a background running download. For the above cases, we can use ajax download Based on the Blod object.
Ajax downloads are the same as ajax uploads. the browser must support ajax2.0. In fact, the so-called download is no different from the normal ajax request. It is a request to a url address, but the download is generally a binary file, not a Text object or json object, javaScript is required to provide a type that encapsulates the binary file, which is blod. Therefore, set the value of responseType of the response type to "blod ":
var xhr =new XMLHttpRequest();xhr.open(option.type ? option.type.toUpperCase() : 'GET', url, true);xhr.responseType = 'blob';
The value of the responseType field of the XMLHttpRequest object must be blob. So what is the blod object?
Blod object
MDN is described as follows:
Blob objects are class file objects that contain read-only raw data. Data in Blob objects is not necessarily in the native form of JavaScript. The File interface is based on Blob, inherits the Blob function, and supports the extension of local files on the user's computer. Using Blob objects, we can encapsulate a binary stream as an object.
If you know html5 file-related APIs, you should be familiar with blod objects. Blod can encapsulate a byte stream as a file, and the responseType value of the XMLHttpRequest object is blob. We can treat the response body as a blob Object.
Xhr. onload = function () {// ignore if (this. status> = 200 & this. status <300) {var blob = new Blob ([this. response], {type: this. response. type });}}
Download the File Using ajax, save the file as a blob object, and cache it in the browser. So how can users save files to the hard disk?
Save blob Object on Hard Disk
We can generate a tag a or iframe and generate a url, which will return to the browser for download. the browser will automatically generate a window for saving attachments. The url can be used. get the createObjectURL (blob) method, URL. createObjectURL supports Blob objects and File objects. It can generate a virtual url so that the current user can access these objects, including download. Different from downloading directly from the server, the downloading here is internal to the client and does not go through network I/O, so the downloading is almost instantaneous. However, after the url is generated, it must be released. Otherwise, the blob resource will not be reclaimed. You can use URL. revokeObjectURL to release the url and release the blob resource. For ie browsers, there is a set of Blob Object processing policies, namely msSaveOrOpenBlob and msSaveBlob navigator methods.
// Download ie if (window. navigator. msSaveOrOpenBlob) {navigator. msSaveBlob (blob, fileName);} else {// non-ie download var link = document. createElement ('A'); link. href = window. URL. createObjectURL (blob); link. download = fileName; link. click (); window. URL. revokeObjectURL (link. href );}
Progress bar and cancel download
Then there is the progress bar and download cancellation function. In fact, the XMLHttpRequest object has a progress event, but we usually ignore it when making ajax requests. After all, the requests are instantaneous, you do not need to set a progress bar for it. However, ajax downloads are different. It takes time to download attachments. Therefore, it is necessary to develop a progress bar for them. By listening to the progress events, we can obtain the download progress.
You can use the abort function of the XMLHttpRequest object to cancel the download. In addition, the load event can be monitored for download completion, and the error event can be monitored for download failure. In short, ajax downloads are exactly the same as events and methods of a common ajax request.
Performance Optimization and same-source policy
Like a persistent connection, ajax downloads consume more bandwidth than normal requests, especially when downloading resources. Therefore, other ajax requests may be blocked during the download process. Therefore, we recommend that you use different domain names for resources downloaded by ajax and other requested resources, however, this will bring about a new problem-same-origin policy issues.
The same-origin policy is the cornerstone of browser security. Any website without the same-origin policy can launch csrf attacks. If the url of the downloaded resource cannot be the same as the url of the current page, the same-origin policy is triggered, causing download failure. Therefore, ajax cross-origin processing is required. Compared with the download method of iframe and the new tab (in fact, iframe also has a same-origin policy, requiring that the pages and parent pages in the iframe cannot access the content of the other party, however, the download function does not involve such operations to access the content of the other party, so iframe download is not affected by the same-origin policy). ajax download is essentially ajax, so it will be affected by the same-origin policy of the browser. Therefore, to download attachments from different sources, the server where the attachment is located must support cors. If the server needs to access cookies, set withCredentials of the XMLHttpRequest object to true.
At the same time, due to the same-origin policy, we cannot use ajax to download third-party resources, because the download service usually does not do cors processing, iframe download or new tab download is not affected by the same-origin policy, so cors is not required. This greatly limits the applicability of ajax downloads.
Summary:
Finally, we will summarize the usage scenarios of ajax download:
1. scenarios where you need to monitor the download progress. For example, if you find that the download progress is too slow, you can provide other solutions.
2. A specific event is triggered after the download is complete. For example, a desktop Notification is displayed.
3. A background download is required. For example, after a user opens a webpage, the user can secretly download the attachment and then cache it. When the user really wants to download the attachment, the attachment can be saved locally. We can even use worker to create a background thread to ensure that the download process does not affect normal page rendering.
4. After downloading the file, it is not saved on the hard disk, but the webapp directly processes the attachment. For example, pdf. js is used for ajax download.
Finally, I will provide the author's ajax download demo: ajaxDownloadDemo_jb51.rar
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.