Home > Article > Backend Development > How to create html browser export and download using JS
This article mainly shares with you the method of creating HTML browser export download with JS. It mainly uses the download attribute and Blob of html5. I hope it can help you.
URL.createObjectURL
The URL.createObjectURL() method will create a URL pointing to the parameter object based on the passed in parameters. The life of this URL only exists in the document in which it is created. . The new object URL points to the executed File object or Blob object.
objectURL = URL.createObjectURL(blob || file);1
File object or Blob object
Here we will briefly talk about File objects and Blob objects:
File object is a file. For example, if I use the input type="file" tag to upload files, then each file inside is a File object.
Blob objects are binary data. For example, objects created through new Blob() are Blob objects. For another example, in XMLHttpRequest, if the responseType is specified as blob, the return value is also a blob object.
*Note
Every time createObjectURL is called, a new URL object is created. Even if you have already created a URL for the same file. If you no longer need this object, to release it, you need to use the URL.revokeObjectURL() method . When the page is closed, the browser will automatically release it, but for optimal performance and memory usage, it should be released when it is ensured that it is no longer needed.
URL.revokeObjectURL
# The ##URL.revokeObjectURL() method will release an object URL created through URL.createObjectURL(). When you have used this object URL, then let the browser know that this URL no longer needs to point to the corresponding file. When, you need to call this method.The specific meaning is that an object URL can be used to access the specified file, but I may only need to access it once. Once it has been accessed, the object URL will If it is no longer needed, it will be released. After it is released, the object URL will no longer point to the specified file.
For example, for a picture, I created an object URL, and then through this object URL, my page This picture is loaded in. Since it has been loaded and there is no need to load this picture again, then I will release the object URL, and then this URL will no longer point to this picture.
var funDownload = function (content, filename) { var eleLink = document.createElement('a'); eleLink.download = filename; eleLink.style.display = 'none'; // 字符内容转变成blob地址 var blob = new Blob([content]); eleLink.href = URL.createObjectURL(blob); // 触发点击 document.body.appendChild(eleLink); eleLink.click(); // 然后移除 document.body.removeChild(eleLink); };Related recommendations:
htmlBrowser displays garbled code_html/css_WEB-ITnose
The above is the detailed content of How to create html browser export and download using JS. For more information, please follow other related articles on the PHP Chinese website!