Javascript сохранить данные файл

How to Create and Save text file in JavaScript?

In this tutorial, we will learn to create and save the text file in JavaScript. Sometimes, developers need to get texts or content from the user and allow users to store content in a text file and allow the file to download to the local computer.

Many JavaScript libraries are available to achieve our goal, but we have used the best two libraries in this tutorial to create and save the text file.

Create a text file using custom text and save it to a local computer

We will use normal JavaScript operations to create and save the text file on the user’s computer. Users can use the HTML tag to create a text file from the custom content and save it.

Developers should follow the below syntax to create a text file from the text input and save it.

Syntax

In the above syntax, we have taken the content from the users, converted it to blog object, and then saved it to the text file.

Algorithm

Users should follow the below steps to understand the above syntax.

Example

We have written the code in the example below by following the syntax and algorithm. We have created the HTML . Users can enter the content they want to add to the file and click on the ‘save file’ button to save the text file on the computer.

When a user clicks on the ‘save file’ button, it will call the ‘downloadFile()’ function, in which we have added the code to create and save the text files.

html> body> h2> Create a text file and save it to a local computer using JavaScript. /h2> p> Enter the file content:- /p> textarea> /textarea> br/> button onclick = "downloadFile()"> save File /button> script> const downloadFile = () => const link = document.createElement("a"); const content = document.querySelector("textarea").value; const file = new Blob([content], type: 'text/plain' >); link.href = URL.createObjectURL(file); link.download = "sample.txt"; link.click(); URL.revokeObjectURL(link.href); >; /script> /body> /html>

Use the FileSaver JavaScript library to create and save the text file

The ‘FileSaver’ is the JavaScript library that we can use to create a text file in vanilla JavaScript. Users can use the CDN of the library to use it with HTML and JavaScript.

Users should use the below syntax to use the FileSaver library.

Syntax

// Create blob object with file content var blob = new Blob(["This is a sample file content."], < type: "text/plain;charset=utf-8", >); // Create and save the file using the FileWriter library saveAs(Content, fileName);

In the above syntax, we have used some text to create the blob object of the ‘text’ type. Also, we have used the ‘saveAs()’ function of the FileWriter library to create and save the text file.

Parameters

The ‘saveAs’ function takes two parameters.

  • Content − It is the content that needs to be stored in the file.
  • filename − It is a default file name when a user downloads it.

Example

We have added the CDN of the ‘FileWriter’ library in the section of the below code. When a user clicks on the ‘create text file’ button, it will invoke the ‘CreateTextFile()’ function in JavaScript, which creates the blob object of the sentence ‘This is a simple file content’ and executes the ‘saveAs()’’function to save the text file.

html> head> script src = "https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js" integrity="sha512-csNcFYJniKjJxRWRV1R7fvnXrycHP6qDR21mgz1ZP55xY5d+aHLfo9/FcGDQLfn2IfngbAHd8LdfsagcCqgTcQ= token operator">= "anonymous" referrerpolicy = "no-referrer"> /script> /head> body> h2>Create text file and save it to local computer using i> FileSaver /i> JavaScript Library./h2> button type = "button" onclick = "CreateTextFile();">Create Text File/button> script> function CreateTextFile() var blob = new Blob(["This is a sample file content."], type: "text/plain;charset=utf-8", >); saveAs(blob, "download.txt"); > /script> /body> /html>

Save the content of the image in a text file using the FileSaver JavaScript library

In this section, we have used the same library, ‘FileSaver’, but rather than storing the normal texts to the file, we string the image after converting the image to a blob object.

Users can follow the syntax below to store the image in the text file format and save it.

Syntax

// Access the file input by Id var element = document.getElementById("uploadedImage"); // Add onchange event to file input element.onchange = function (event) < // Convert image content to text var blob = new Blob[event.target.files[0]], < type: "text/plain;charset=utf-8", >); // Create text file using image’s content and save it saveAs(blob, "download.txt"); >;

In the above syntax, we take the file the user uploads into the HTML and convert its content to a blob object. After that, we create the text file using the blob object and save the file to the local computer.

Example

We have used the ‘FileSaver’ JavaScript library in the example below, as shown in the above syntax. We have created the file input field, allowing users only to upload the image file.

In JavaScript, we have added the event listener to the file input, and as the user uploads a file, it will create a text file using the uploaded image file and save it to the user’s computer.

html> head> script src = "https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js" integrity = "sha512-csNcFYJniKjJxRWRV1R7fvnXrycHP6qDR21mgz1ZP55xY5d+aHLfo9/FcGDQLfn2IfngbAHd8LdfsagcCqgTcQ= token operator">= "anonymous" referrerpolicy = "no-referrer"> /script> /head> body> h2>Upload image and add its content to text file and save it to computerusing i> FileSaver /i> JavaScript Library./h2> input type = "file" id = "uploadedImage" accept = "image/png, image/gif, image/jpeg"/> script> var element = document.getElementById("uploadedImage"); element.onchange = function (event) var blob = new Blob[event.target.files[0]], type: "text/plain;charset=utf-8", >); saveAs(blob, "download.txt"); >; /script> /body> /html>

Источник

JavaScript | Как сохранить строку (данные) в файл на клиенте (браузере)?

Задача примитивно простая — нужно сохранить строку из браузера в какой-нибудь файл на компьютере или ноутбуке. Строка представляет собой полезные данные.

Пусть у нас будет строка, которую мы создадим на вкладке Console в инструментах разработчика браузера:

let stroka color: #993300;">BlaBla Bla HHHmm"

Мы хотим сделать так, чтобы наш браузер загрузил файл на компьютер с этой строкой внутри.

Не важно каким образом мы получаем строки, главное что эта строка хранится в какой-то переменной и мы хотим сохранить содержимое этой переменной.

Может пользователь что-то печатает в Input и сохраняет, может текст генерируется автоматически без пользовательской помощи. Не важно. Главное — это сохранить данные в файл на клиентской стороне без привлечения сервера.

Как это сделать?

Существует несколько способов реализации задуманного.

Видео на 30 минут с пояснениями клиентского сохранения строки

Способ № 1 — Использование конструкторов Blob и URL

Логика такая. Сначала создаём новый большой двоичный объект — Blob . По сути это файл.

let blob = new Blob([stroka], text/plain">)

Конструктор Blob() принимает 2 параметра — СТРОКУ и её ТИП.

СТРОКА помещается в квадратные скобки и становится первым элементом массива, а ТИП помещается в фигурные скобки. Строкой у нас является переменная stroka , а объект с типом является

Затем создаём новый объект ссылки (HTML-элемент) при помощи объектной модели документа DOM и метода createElement() :

let link = document.createElement("a")

Сейчас эта ссылка хранится в переменной link и её не видно в документе. О её существовании знает только консоль браузера и оперативная память компьютера пользователя. Эта ссылка не содержит никаких атрибутов. Сейчас она выглядит так:

Теперь нам нужно немного оживить наш элемент ссылки. Сперва добавим атрибут href для элемента . В качестве значения атрибута у нас будет выступать адрес URL . createObjectURL ( blob )

link.setAttribute("href", URL.createObjectURL(blob))

Пример адреса, который может быть в href. Запущен во вкладке «Экспресс-панели» браузера Opera.

URL.createObjectURL(blob) "blob:chrome://startpage/388da889-5981-4b67-8966-567b109b8612"

Мы видим, что ссылка будет использовать URI-схему « blob: »

blob, ссылка и её href - JavaScript

Теперь нам нужно добавить ещё один атрибут для нашей ссылки. Это атрибут — download. Значением атрибута будет название файла для скачивания.

link.setAttribute("download", "my-text.txt")

Быстренько глянем на объект ссылки перед финальным действием.

Готовая ссылка для клика - JavaScript

Мы видим, что ссылка готова к нажатию на неё мышкой. Но мы не будем выводить эту ссылку в документ и не будем кликать на неё мышкой физически.

Вместо этого мы скажем JavaScript самому нажать на «невидимую» ссылку. Мы выполним событие клика за пользователя. Просто введём с консоль браузера:

Вызвали событие клика - Файл скачался - JavaScript

Смотрим что в файле на ПК:

Файл успешно создался и скачался - JavaScript

Мы скачали файл с данными, которые получили на клиенте (в браузере)

Весь код без комментариев — Запусти в консоли браузера, протестируй!

let stroka color: #993300;">BlaBla Bla HHHmm"; let blob = new Blob([stroka], text/plain">); let link = document.createElement("a"); link.setAttribute("href", URL.createObjectURL(blob)); link.setAttribute("download", "my-text.txt"); link.click();

Функция сохранения строки (данных) в файл на ПК из браузера

function saveToPC(str) < let blob = new Blob([str], text/plain">); let link = document.createElement("a"); link.setAttribute("href", URL.createObjectURL(blob)); link.setAttribute("download", Date.now()+""); link.click(); >

Источник

Читайте также:  Java static class compile
Оцените статью