Save File Locally in Browser with JavaScript

To save a file locally in JavaScript, we recommend using the FileSaver library.

To install the FileSaver library, you can use the npm package manager. Here is an example of how to do this:

npm install file-saver

Once the library is installed, you can use it in your JavaScript code by importing it like this:

import saveAs from 'file-saver';
Code language: JavaScript (javascript)

Now, here is an example of using the imported saveAs method to save a file locally:

// Create a Blob (binary large object) representing the file you want to save var file = new Blob([data], {type: 'text/plain'}); // Use the FileSaver library to save the file saveAs(file, 'my-file.txt');
Code language: JavaScript (javascript)

In this example, data is the data that you want to save in the file, 'my-file.txt' is the name that you want to use for the saved file, and text/plain is the content type. The saveAs() method will automatically download the file to the user’s computer.

In your code you will want to change the text/plain content type and the my-file.txt filename as appropriate.

For example, if you want to save a CSV file then you should use text/csv and use a filename that ends with .csv.

You can reference MDN’s Common Mime Types guide to help figure out what sort of content type to set.

You can find more information about the FileSaver library on its GitHub page.

Alternative Method

If you don’t want to use a third-party library, you can use the below method. It works the same as FileSaver but will lack some browser support. However, it should work in all major browsers.

Here’s an example of how you could use a Blob to save a file from a browser:

// Create a Blob from the file data. var blob = new Blob(['This is the file content.'], { type: 'text/plain' }); // Create a URL that points to the Blob. var url = window.URL.createObjectURL(blob); // Create a link element. var link = document.createElement('a'); // Set the link's href attribute to the Blob URL. link.href = url; // Set the link's download attribute to specify the filename. link.download = 'my-file.txt'; // Add the link to the page. document.body.appendChild(link); // Click the link to trigger the download. link.click(); // Cleanup window.URL.revokeObjectURL(url); document.body.removeChild(link);
Code language: JavaScript (javascript)

This code will create a Blob object from the file data, create a URL that points to the Blob, and then use this URL to create a link element that is automatically clicked which triggers the download.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *