-1

I'm currently developing a website in HTML and don't know how to take form input. I would like it to be able to go into a text file with other answers. Currently I have a local .txt file that I want the string to go into.

graph100
  • 57
  • 7
  • Welcome to Stack Overflow! In order to accomplish your goal, you'd need an endpoint to which your form _posts_ the form data. In this handler, usually a REST endpoint, you can write code to store the form data into a text file. TL;DR: You'll need a backend system(Java, PHP, NodeJS, etc.) in place to be able to do what you want to do. – Vikram Deshmukh Jan 31 '20 at 23:24
  • HTML is a static language, meaning you cannot do any kind of processing with it. On top of that, it is also a front-end language that is run inside of a browser. Browsers do not give websites access/create local files, as that would be a ginormous security risk. With JavaScript this is a little more do-able, but it is still a front-end language ran in the browser. I would recommend writing a back-end in PHP, ASP.NET, or node.js to do this. You can then use HTML's forms to be able to submit the contents to something that has access to files on the local server. – Jesse Jan 31 '20 at 23:25

1 Answers1

0

Before HTML5, you couldn't do this. In fact, my answer was going to be that you can't do this with HTML and JavaScript, due to it being a security breach. But it seems that people do occasionally need to do it and now there's a way, without going around security protocols.

To be able to save files and folders from inside the web browser to the local hard drive you’ll need access to the filesystem. As this means a potential enormous security breach, it is not permitted by default. As a compromise between all or nothing, the FileSystem-API is only allowed to access a specific protected area on your local drive controlled by the browser.

https://www.jotform.com/blog/html5-filesystem-api-create-files-store-locally-using-javascript-webkit/

This article goes on to say how it can be done in HTML5, though, or rather JavaScript in an HTML5 document.

window.webkitRequestFileSystem(window.TEMPORARY, 1024*1024, SaveDatFileBro);
window.webkitRequestFileSystem(window.PERSISTENT , 1024*1024, SaveDatFileBro);

navigator.webkitPersistentStorage.requestQuota(1024*1024, function() {
  window.webkitRequestFileSystem(window.PERSISTENT , 1024*1024, SaveDatFileBro);
})
function SaveDatFileBro(localstorage) {
  localstorage.root.getFile("info.txt", {create: true}, function(DatFile) {
    DatFile.createWriter(function(DatContent) {
      var blob = new Blob(["Lorem Ipsum"], {type: "text/plain"});
      DatContent.write(blob);
    });
  });
}

This means you need to get the values from the HTML form into JavaScript.

HTML:

<input type="text" name="name" id="uniqueID" value="value" />

JS:

var nameValue = document.getElementById("uniqueID").value;

JavaScript - Getting HTML form values

computercarguy
  • 2,173
  • 1
  • 13
  • 27