I'm trying to put the displayed values in the tag on a csv file. However when I export, I download an empty file. What am I doing wrong?
document.getElementById("export").addEventListener("click",function(){ var file; var download = document.getElementById("fileContents").textContent; download = file; },false)
<!DOCTYPE html> <html lang="pt-pt"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <input type="file" id="openFile"/> <a id="export" download="export.csv" href="data:text/html,">Export</a> <br> <br> <br> <!-- preformatted text --> <pre id="fileContents"> ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo</pre> <!--/preformatted text --> <!-- app.js --> <script src="js/app.js"></script> </body> </html>
You can add the text content to the <a>
element, by adding one more line in your script:
document.getElementById("export").addEventListener("click",function(){
var download = document.getElementById("fileContents").textContent;
// adds text to <a> element
this.setAttribute('href', 'data:text/html,' + encodeURIComponent(download));
},false)
You can construct a file to download via a data URI . To do this, you set the 'href' attribute of the anchor tag to the data URI encoding the file you want to download. If you use a plain text (not base64) URI, be sure and URL-escape the string you are encoding.
document.getElementById("export").addEventListener("click",function(){ let dataUri = 'data:text/html,' + encodeURIComponent(document.getElementById("fileContents").textContent); this.href = dataUri; },false)
<!DOCTYPE html> <html lang="pt-pt"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <input type="file" id="openFile"/> <a id="export" download="export.csv" href="data:text/html,">Export</a> <br> <br> <br> <!-- preformatted text --> <pre id="fileContents"> ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo ojdaoj,feokokfe,dawff,efofewfo</pre> <!--/preformatted text --> <!-- app.js --> <script src="js/app.js"></script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.