简体   繁体   中英

Javascript — How to save a txt file with HTA

I am creating an HTA application that sits on a shared drive. I have a section in which the app generates a report txt file and should allow the user to save it.

I'd like the user to be able to pick where to save it and what to call it, as you would any time you save a file, but I can't figure out how to accomplish it. The best way I've come up with so far is to save the file, offer it up for download so they can pick a location that suits them (and a name), and then delete the automatically saved version afterward. This sounds hacky and more clunky than it should. Is there a better way?

EDIT: Commenter asked for the code I used to serve the download:

I had a textarea in the html that contains the report text --

<textarea id="reportText" class="col-md-12 form-control"></textarea>

Then a save file button:

<a class="btn btn-success" id="saveReportBtn">Save File</a>

When generating the report, the code adds the href and download attributes to the "Save File" button:

document.getElementById('saveReportBtn').href = "data:text/plain, TEST";
document.getElementById('saveReportBtn').setAttributeNS(null, "download", "");

Yet, nothing happens when I click the button. I also tried giving download a recommended filename, (null, "download", "myFile.txt").

You could use an a element, download attribute, with href attribute set to objectURL or data URI of file. The Save File dialog should display when user clicks a element , where user can name file and select where to save file at user filesystem

 var a = document.getElementById("saveReportBtn"); var textarea = document.getElementById("reportText"); a.addEventListener("click", function() { this.href = "data:application/octet-stream," + encodeURIComponent(textarea.value); // this.download = ""; }); 
 <textarea id="reportText" class="col-md-12 form-control"></textarea> <a href="" class="btn btn-success" id="saveReportBtn">Save File</a> 

jsfiddle using download attribute https://jsfiddle.net/h51dhdgn/ ; see download

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM