user2593758
user2593758

Reputation: 997

It it possible to use javascript to save a file to same directory as current file?

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?

Upvotes: 3

Views: 16395

Answers (2)

slevy1
slevy1

Reputation: 3832

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");
    });

Upvotes: 2

Alex Bieg
Alex Bieg

Reputation: 365

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.

Upvotes: 2

Related Questions