In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you the relevant knowledge points about how to use download in html5. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Introduction to download attribute
Regular tags use href to redirect links. If you only want to download files instead of jumping previews, the best way is to add the download attribute to the tags, and you can easily download them.
Download is a new attribute of the tag in HTML5, which forces the download operation to be triggered, instructs the browser to download URL instead of navigating to it, and prompts the user to save it as a local file, for example:
Download
If the download attribute is missing, clicking "download" will directly turn into a preview image, and when you add the download attribute, it will trigger the download of the image.
Currently, the compatibility of download attributes is shown in caniuse:
It can be seen that most mainstream browsers have basically supported the download attribute, and the performance of IE is as touching as ever. At present, many Window systems are still using IE, which is also a lot of business needs to consider. This compatibility issue limits the wider use of download.
Dynamic resource download
Faced with some business scenarios of dynamic content download, that is, the address of resources such as pictures is not fixed (for example, images generated by some online drawing tools), only using HTML can not meet the demand. In order to satisfy different URL downloads, you can implement a method of dynamically triggering URL downloads through JS.
Function download (href, filename='') {const a = document.createElement ('a') a.download = filename a.href = href document.body.appendChild (a) a.click () a.remove ()}
It should be noted that the appendChild and remove operations on the creation in the code are mainly for compatibility with FireFox browsers. If the created tags are not added to the body in FireFox browsers, there will be no reaction when you click on the link, which will not trigger the download, but will not be affected in Chrome browsers.
The above method can realize the download of homologous resources. However, in many scenarios, you also need to deal with cross-domain resources. Unfortunately, the download attribute currently only applies to the same origin URL, that is, if the resource address you need to download is cross-domain, the download attribute will become invalid and the link will become a navigation preview.
Test: click download, the result is only a preview and can not download the picture.
Note: Chrome65 previously supports download attribute to trigger cross-domain downloading of files, but then strictly follows the same origin policy, and can no longer trigger cross-domain resource downloads through the download attribute. However, FireFox does not support downloading the download attribute of cross-domain resources.
File naming problem
The download attribute can not only trigger the download, but also specify the download file name:
download
If the suffix of the download file is the same as the source file, you can set the default file name:
download
The author has encountered a problem. The code of the cross-domain resource download triggered by the tag is basically the same as the download method mentioned above, except that the download attribute is set a little different:
A.setAttribute (download, true)
As a result, the following occurs in older versions of Chrome browsers.
The download file name is true. Obviously, the browser reads the value of the download attribute as the file name.
After analysis, the above problems are mainly due to:
1. Download should not have been set to true in the first place. Download is different from the property value of the type disabled, which is directly associated with the file name. And for this front-end responsive download, the download attribute is not necessary.
two。 Earlier versions of Chrome not only supported downloading the download attribute of cross-domain resources, but also reset the file names of cross-domain resources through download, which is why this happened.
The business scenario in which the front and rear end cooperates to complete the file download is generally realized by setting the Content-Disposition information in the response header at the back end.
In the HTTP scenario, the first parameter of Content-Disposition is either inline (the default value, which means that the message in the reply will be displayed as part of the page or the whole page), or attachment (which means that the message body should be downloaded locally; most browsers will present a "save as" dialog box, prepopulating the value of filename with the downloaded file name).
If Content-Disposition is set in the response header and the download attribute is added to the tag of the corresponding link at the front end, then the naming rule is as follows:
If the Content-Disposition attribute in the HTTP header is assigned a different file name than this property, the HTTP header attribute takes precedence over this attribute.
After testing, it is found that when the Content-Disposition in the HTTP header is not empty:
In Chrome browsers, download cannot reset the file name as long as filename is set, regardless of whether the first parameter of Content-Disposition in the HTTP header is set to attachment or inline. Conversely, when filename is empty, the value of the download property is set to the file name. In FireFox browsers, the browser only reads the filename value of Content-Disposition. If filename is empty, the source file name is taken. At this point, download cannot reset the file name anyway.
To sum up: the Content-Disposition information is not set in the response header (for example, the homologous URL of the resource is generally located directly), and the download attribute can reset the file name. If the backend has set filename in the Content-Disposition field, the value of filename shall prevail.
What if you still want to reset the file name when the backend has already set the file name?
Blob: URL
There is also an introduction to the download property:
Although HTTP URL needs to be in the same source, you can use blob: URL and data: URL to make it easy for users to download content generated using JavaScript (for example, photos created using an online drawing Web application).
Blob (Binary Large Object) is a binary large object, which is no stranger to us. Some databases use Blob to represent the field type in which binary files are stored. The File interface is also based on Blob, inheriting the functions of Blob and extending it to support files on the user's system. The Blob object is created through the Blob constructor:
Blob (blobParts [, options])
Var debug = {hello: "world"}; var blob = new Blob ([JSON.stringify (debug, null, 2)], {type: 'application/json'})
If you need to download some simple files such as text or JS strings, you can generate a Blob URL by converting the text information into a blob binary stream, and complete the download with the download attribute as follows.
Const downloadText = (text, filename ='') {const a = document.createElement ('a') a.download = filename const blob = new Blob ([text] {type: 'text/plain'}) / / text refers to the text or string content that needs to be downloaded a.href = window.URL.createObjectURL (blob) / / generates a URL string such as blob: http://localhost:8080/d3958f5c-0777-0845-9dcf-2cb28783acaf document.body.appendChild (a) a.click () a.remove ()}
What is the difference between this Blob URL and a common HTTP URL?
Blob URL / Object URL is a pseudo-protocol that allows Blob and File objects to be used as URL sources such as image and binary data download links.
The browser internally creates a special reference to the Blob or File object through URL.createObjectURL (). The generated Blob URL can only be used in a single instance of the browser and in the same session, and the URL object is released by the browser when the page exits.
So Blob URL can't point to a server resource, and you can't open it in other pages. At the same time, because of the difference in coding format, Blob URL takes up less space resources and better performance than Data URLs.
Blob provides a very useful feature for Web development: creating Blob URL. Encapsulate binary data as Blob objects, and then use URL.createObjectURL () to generate Blob URL. Because Blob URL itself is a homologous URL, you can use this URL with download to solve the problem of downloading and naming cross-domain resources.
Solution
The problem of cross-domain and file naming can be solved through Blob and Fetch: use fetch to obtain cross-domain resources, return a blob object and generate a Blob URL, and trigger the download with the download attribute of the tag, as follows:
Function download (href, filename='') {const a = document.createElement ('a') a.download = filename a.href = href document.body.appendChild (a) a.click () a.remove ()} function downloadFile (url, filename='') {fetch (url, {headers: new Headers ({Origin: location.origin,}), mode: 'cors' Res = > res.blob () .then (blob = > {const blobUrl = window.URL.createObjectURL (blob) download (blobUrl, filename) window.URL.revokeObjectURL (blobUrl)})}
Click download again at this time, you can download the cross-domain images to the local area normally.
It is important to note that the server where the cross-domain resources are located needs to be configured with Access-Control-Allow-Origin information, otherwise you will get an uppercase cross-domain error. Header configuration for example:
/ / allow any domain name to access header ('Access-Control-Allow-Origin: *'); / / specify a domain name to access header ('Access-Control-Allow-Origin: https://h6.ele.me');
At present, this method still has some shortcomings, such as browsers will limit the size of Blob data to no more than 500m, and there will be some deficiencies in terms of performance.
These are all the contents of the article "how to use download in html5". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.