简体   繁体   English

Javascript —如何使用HTA保存txt文件

[英]Javascript — How to save a txt file with HTA

I am creating an HTA application that sits on a shared drive. 我正在创建位于共享驱动器上的HTA应用程序。 I have a section in which the app generates a report txt file and should allow the user to save it. 我有一个部分,其中应用程序生成报告txt文件,并应允许用户保存它。

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 -- 我在html中有一个文本区域,其中包含报告文本-

<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: 生成报告时,代码将href和download属性添加到“保存文件”按钮:

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"). 我还尝试为下载提供建议的文件名(空,“下载”,“ myFile.txt”)。

You could use an a element, download attribute, with href attribute set to objectURL or data URI of file. 你可以使用a元素, download属性,与href设置为属性objectURLdata URI文件。 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 当用户单击a元素时,将显示“ Save File对话框,用户可以在其中命名文件并选择在用户文件系统中将文件保存在何处

 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/ ; jsfiddle使用download属性https://jsfiddle.net/h51dhdgn/ ; see download 查看download

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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