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 target="_blank" href="download.zip" rel="external nofollow" >点击下载</a> //或者 <iframe style="display:none" src="download.zip"></iframe>
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.var xhr =new XMLHttpRequest(); xhr.open(option.type ? option.type.toUpperCase() : 'GET', url, true); xhr.responseType = 'blob';
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}); } }
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的下载 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!