Команда сохранить файл 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>

Источник

How to Save Files in JavaScript

Save As

In the web world, saving a file or “Save As” means downloading a file to the client’s machine. There isn’t a built-in method in JavaScript that allows us to do so. What we typically do (if we have a static file link) is add an anchor element in HTML and use the download attribute to make it downloadable. Something like this:

a href="/images/myFile.txt" download>

The problem is that we don’t always want the user to download when clicking on a link because we could have a bunch of logic before downloading or some dynamic data created without a static link. Let’s go through a few simple steps to create a saveAs function for downloading one or multiple files in JavaScript!

Unless we have static files available publicly on the server, we need to create content using a Blob , a file-like object in JavaScript.

Let’s create a function that will take some data as a parameter and return a new Blob text:

function createBlob(data)   return new Blob([data],  type: "text/plain" >); >

Of course, a Blob object has a lot more than just a plain text type. You can learn more in the official documentation.

Let’s look at two approaches for saving/downloading a file in JavaScript:

1. Use an Anchor element

We can dynamically create an anchor element in JavaScript using createElement and then programmatically invoke the click event. Here is a basic example:

const a = document.createElement("a"); a.click();

But to download a file, we need to pass it download and href attributes. The download will hold the file name and extension and the href will require a URL. Let’s create a function and put all the implementation together:

If we are using a static file with a relative path, all we need to do is this:

function saveAs()   const a = document.createElement("a");  a.href = '/files/myFile.txt';  a.download = "myFile.txt";  a.click(); >

Download only works for same-origin URLs. Meaning, href can’t be a path different than your websites’ otherwise the behavior will change and it will redirect instead of downloading.

If the content is generated dynamically, we’ll need to create a blob and convert it to an object URL to make it downloadable. Also, we need to release the object at the very end when no longer needed:

function saveAs()   const a = document.createElement("a");  const file = createBlob("Hello Blob!!");  const url = window.URL.createObjectURL(file);  a.href = url;  a.download = "myFile.txt";  a.click();  URL.revokeObjectURL(); >

Let’s improve the function to make it re-usable and have it support both options:

function saveAs(content, fileName)   const a = document.createElement("a");  const isBlob = content.toString().indexOf("Blob") > -1;  let url = content;  if (isBlob)   url = window.URL.createObjectURL(content);  >  a.href = url;  a.download = fileName;  a.click();  if (isBlob)   window.URL.revokeObjectURL(url);  > > // Consume the function as follows: const file = createBlob("Hello, file!"); saveAs(file, "myFile.txt");

2. Use file-saver library

FileSaver.js is a great solution to saving files on the client-side without having to write our own custom code.

First, we need to install the library:

const FileSaver = require('file-saver'); // Save Blob file const file = createBlob('Hello, file!'); FileSaver.saveAs(file, "myFile.txt"); // Save URL FileSaver.saveAs("https://httpbin.org/image", "image.jpg");

Zip and download multiple files

In certain cases, we need to download multiple files in one hit. Although this can be achieved by looping through the files and triggering the saveAs function, the user experience isn’t great and we’ll end up with so many files added to the download folder.

An alternative solution is to use JSZip, a library for creating, reading, and editing .zip files.

First, we need to install the library:

Then, we’ll create an async function that does the following logic:

const file1 = createBlob("Hello Blob 1!"); const file2 = createBlob("Hello Blob 2!");
const zip = new JSZip(); zip.file("file1.txt", file1); zip.file("file2.txt", file2);
  1. Generate the zip folder and as soon as it’s ready, we can call the saveAs function we did earlier:
const content = await zip.generateAsync( type: "blob" >); saveAs(content, "folder.zip");

Here is the full function:

async function zipFiles()   const zip = new JSZip();  const file1 = createBlob("Hello, file 1!");  const file2 = createBlob("Hello, file 2!");  zip.file("file1.txt", file1);  zip.file("file2.txt", file2);  const content = await zip.generateAsync( type: "blob" >);  saveAs(content, "folder.zip"); >

I hope you enjoyed learning from this article and if you have any questions, please leave a comment below.

Источник

Читайте также:  Javascript фильтрация массива объектов
Оцените статью