I have 5 text fields in which there are some values.

How to implement export and import to a file? Ie, the point is that all the entered values ​​go into the file, and later they can be opened.

Google search returned no results, because I found solutions only in PHP.

  • In the file on the client or on the server? - Ella Svetlaya
  • There is no client-server in the interaction. a local page with text fields which, when filled, should be output to a file, and let's say there are a lot of such files selected, we have loaded everything into our text fields. - Paul
  • File API. read carefully. You can both read from files and save to files, not only in the local storage, but also in any place. you just need to know how to use js and search, both on the server and on the client. - Vadim

3 answers 3

File System API - not standardized and not approved by the W3C API, which will only work in browsers on the Blink engine. This option will suit you only if you are writing an add-on for Chrome or a web application for a specific browser.

If not, use the standardized FileReader API , which works on almost all modern browsers .

Example of writing and reading a file (or several):

HTML:

<input id="input" type="file"> <hr> <textarea id="textarea"></textarea> <hr> <a id="download" href="">Скачать файл</a> 

Javascript:

 var inputElement = document.getElementById('input'), downloadElement = document.getElementById('download'), textareaElement = document.getElementById('textarea'); downloadElement.style.display = 'none'; inputElement.onchange = function() { var fileList = this.files, // список указанных файлов textFile = fileList[0]; // для нашего примера берём один файл // Проверяем тип файла (текстовой файл) if (textFile.type == 'text/plain') { // Создаём новый FileReader, который и будет читать наш файл var reader = new FileReader(); // Событие успешного чтения reader.onloadend = function(event) { var text = event.target.result, blob = new Blob([text], { type: 'text/plain' }); // Ваши любые манипуляции с данными textareaElement.value = text; downloadElement.style.display = 'block'; downloadElement.href = URL.createObjectURL(blob); downloadElement.download = textFile.name; }; // Событие ошибки reader.onerror = function() { alert('Ошибка чтения файла!'); }; // Читаем наш файл как текст reader.readAsText(textFile); } else { alert('Это не текстовой файл!'); } }; textareaElement.onkeyup = function() { // Обновляем ссылку скачивания файла // (ТОЛЬКО ДЛЯ ПРИМЕРА, СКРИПТ ВЫПОЛНЯЕТСЯ ПРИ КАЖДОМ НАЖАТИИ КЛАВИШИ) var text = this.value, blob = new Blob([text], { type: 'text/plain' }); downloadElement.href = URL.createObjectURL(blob); }; 

P.S. I can’t add more than two links to the answer (due to a reputation limit), but a search on "FileReader API" will give you many additional hints and examples;)

    There are several options with their own advantages and disadvantages. See the proposed solutions here and here .

    Examples of solutions:

    1) generate a file and follow the link to suggest the user to download it. Implementation:

     function download(text, name, type) { var a = document.getElementById("a"); var file = new Blob([text], {type: type}); a.href = URL.createObjectURL(file); a.download = name; } 
     <a href="" id="a">click here to download your file</a> <button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button> 

    2) Use the FileSystem API - http://www.html5rocks.com/en/tutorials/file/filesystem/

    See also https://developers.google.com/web/updates/2011/08/Saving-generated-files-on-the-client-side

      If you want to use javascript for this purpose, then node.js is right for you.

      • And how does it fit? - Qwertiy