admin管理员组

文章数量:1313178

I am writing JavaScript code which is executed in a local web server. Is it possible to have that code generate another file, which is then added to the same directory as the original file? If so, how?

I am writing JavaScript code which is executed in a local web server. Is it possible to have that code generate another file, which is then added to the same directory as the original file? If so, how?

Share Improve this question asked Jun 23, 2017 at 21:28 user2593758user2593758 9972 gold badges11 silver badges17 bronze badges 2
  • Please be more precise. Are you running the code clientside or serverside? – Chris Satchell Commented Jun 23, 2017 at 21:34
  • NodeJS is technically javascript and server side – ConnerAiken Commented Jun 23, 2017 at 21:42
Add a ment  | 

2 Answers 2

Reset to default 2

Things have greatly changed with HTML5 and so the answer is "Yes!" provided that one is using a modern browser and/or one takes advantage of JavaScript libraries that may aid with this endeavor. Take a look here as well as here. If you alter your browser's download settings to the desired folder of your local web server, when you submit the form the file will be downloaded there. I tried this using google chrome 49 on a windows box using wampserver and the file was saved exactly in the specified folder. After forking the code here, it ran successfully on my local webserver from the directory where I wanted the new file to be downloaded.

The pertinent jQuery code from codepen.io:

$("#btn-save").click( function() {
      var text = $("#textarea").val();
      var filename = $("#input-fileName").val()
      var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
      saveAs(blob, filename+".txt");
    });

I am not an expert on this, but I will try to help out. From my understanding the only way to create a file on the server is to have server side code do it. You could have the javascript call some endpoint and that could create the file. But I believe it is impossible to directly create the file.

本文标签: htmlIt it possible to use javascript to save a file to same directory as current fileStack Overflow