JavaScript saves examples of text data, not just text but also other types.
First up the code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script> var fl; function g(f) { fl = null; if(f) { document.getElementById("fname").innerText = f.name; document.getElementById("fsize").innerText = f.size; fl = f; } } function dataURLSave1() { if(fl) { var reader = new FileReader(); reader.onload = function(e) { ck(e.target.result); }; reader.readAsDataURL(fl); } } function dataURLSave2() { if(fl) { var reader = new FileReader(); reader.onload = function(e) { ck('data:text/plain;charset=utf-8,' + e.target.result); }; reader.readAsText(fl); } } function objectURLSave() { if(fl) { ck(URL.createObjectURL(fl)); setTimeout(function(){ URL.revokeObjectURL(fl);//Release the object URL with the URL. revokeObject URL () },200); } } function ck(href) { document.getElementById("hf").href = href; document.getElementById("hf").download = fl.name; document.getElementById("hf").click(); } </script> </head> <body> <input type="file" onchange="g(this.files[0])"> <div>file name:<span id="fname"></span></div> <div>Size:<span id="fsize"></span></div> <button onclick="dataURLSave1()">Preservation(dataURL Mode 1)</button> <button onclick="dataURLSave2()">Preservation(dataURL Mode 2)</button> <button onclick="objectURLSave()">Preservation(objectURLSave mode)</button> <a id="hf" href="" download="download"></a> </body> </html>
Implementation classification
Generally speaking, there are two simple ways to export similar and text files by using browser's own functions.
1.DataURL
2.ObjectURL
principle
In fact, the principle of download is the same as usual, but the connection of download is replaced by the above two URL s.
compare
Data URL approach
In the sample code, Data URL mode 1 reads the text file directly into a Data URL, and Data URL mode 2 reads the text content and splices it with (data:text/plain;charset=utf-8,...)
Data URL mode 1 and data URL mode 2 have certain requirements for file text encoding and are prone to scrambling.
Object URL approach
Object URLs convert objects in memory into Object URLs. Object URLs are less likely to be scrambled than DataURLs, but DataURLs are more fixed than Object URLs.