Introduction to file-saver
The file-saver library is a powerful and convenient tool used for client-side file saving in web applications. Whether you are generating files dynamically or offering downloads, file-saver comes with a host of APIs to make the task straightforward. This article delves into various APIs provided by file-saver along with practical examples.
Installing file-saver
First, you need to install file-saver via npm or yarn:
npm install file-saver
// or
yarn add file-saver
API Methods
saveAs
The primary method in file-saver is saveAs
. This method allows you to trigger a file download dynamically.
import { saveAs } from 'file-saver';
// Saving a simple text file
const blob = new Blob(["Hello, world!"], { type: "text/plain;charset=utf-8" });
saveAs(blob, "hello_world.txt");
saveAs from URL
You can also save files from URLs using the same saveAs
method:
import { saveAs } from 'file-saver';
// Saving a file from URL
const fileUrl = "https://example.com/file.pdf";
saveAs(fileUrl, "downloaded_file.pdf");
Multiple File API Examples
Saving JSON Data
To save JSON data as a file:
import { saveAs } from 'file-saver';
const data = { name: "John", age: 30, city: "New York" };
const json = JSON.stringify(data);
const blob = new Blob([json], { type: "application/json" });
saveAs(blob, "data.json");
Saving Images
Saving images is just as straightforward:
import { saveAs } from 'file-saver';
const image = new Blob(["(binary data)"], { type: "image/png" });
saveAs(image, "image.png");
Saving CSV Data
To save a CSV file:
import { saveAs } from 'file-saver';
const csv = "name,age,city\nJohn,30,New York";
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
saveAs(blob, "data.csv");
App Example
Here is an example of a simple app that uses file-saver to download user-generated content based on selections made in the app:
import React, { useState } from 'react';
import { saveAs } from 'file-saver';
const App = () => {
const [text, setText] = useState('');
const handleSave = () => {
const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
saveAs(blob, "user_text.txt");
};
return (
Text Saver
);
};
export default App;
With this app, users can input text into a textarea, and upon clicking the “Save Text” button, file-saver will download the content as a text file.
Hash: bcc58f7d906db554a4ad7e988c4489f46e1737bfd7eff1f62d5b37e2bed5d3c1