save a field value to a file on desktop

大兔子大兔子 提交于 2019-12-12 05:59:50

问题


I am developing a custom application in "ServiceNow" which requires Javascript and HTML coding. So, I have a field say, "description" on my form. How may I save this field's value to a word document on the desktop?


回答1:


While JavaScript cannot create a file for you to download by itself, ServiceNow does have a way for you to create one. Creating a Word document is impossible without the use of a MID server and some custom Java code, but if any file type will do you can create an Excel file using an export URL. To test this out, I made a UI Action in a developer instance running Helsinki on the Problem table. I made a list view that contains only the field that I wanted to save, and then used the following code in the UI action:

    function startDownload() {
    window.open("https://dev13274.service-now.com/problem_list.do?EXCEL&sysparm_query=sys_id%3D" + 
        g_form.getUniqueValue() + "&sysparm_first_row=1&sysparm_view=download");
}

When the UI action is used, it opens a new tab that will close almost immediately and prompt the user to save or open an Excel file that contains the contents of that single field.

If you want to know more about the different ways you can export data from ServiceNow, check their wiki-page on the subject.




回答2:


You can use the HTML5 FileSystem API to achieve that

window.requestFileSystem(window.PERSISTENT, 1024*1024, function (fs) {
  fs.root.getFile('file.txt', {create: true}, function(fileEntry) {
    fileEntry.createWriter(function(fileWriter) {
      var blob = new Blob([description.value], {type: 'text/plain'});
      fileWriter.write(blob);
    });
  });
});

FYI, chrome supports webkitRequestFileSystem.

Alternatively, use a Blob and generate download link

var text = document.getElementById("description").value;
var blob = new Blob([text], {type:'text/plain'});
var fileName = "test.txt";

var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.href = window.webkitURL.createObjectURL(textFile);
downloadLink.click();



回答3:


Javascript protects clients against malicious servers who would want to read files on their computer. For that reason, you cannot read or write a file to the client's computer with javascript UNLESS you use some kind of file upload control that implicitely asks for the user's permission.



来源:https://stackoverflow.com/questions/37309332/save-a-field-value-to-a-file-on-desktop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!