@giapspzoo/save-file
v1.0.0
Published
A TypeScript utility for saving files in the browser.
Readme
@giapspzoo/save-file
A TypeScript utility for saving files in the browser.
Installation
npm install @giapspzoo/save-fileUsage
import saveFile from "@giapspzoo/save-file";
// Save a file from URL with custom filename
saveFile({
fileName: "my-document.pdf",
url: "https://example.com/document.pdf",
});
// Save a file from URL without custom filename (uses original filename)
saveFile({
url: "https://example.com/document.pdf",
});
// Save a file from Blob
const blob = new Blob(["Hello, World!"], { type: "text/plain" });
const blobUrl = URL.createObjectURL(blob);
saveFile({
fileName: "hello.txt",
url: blobUrl,
});
URL.revokeObjectURL(blobUrl); // Don't forget to revoke the blob URL when done
// Save an image from Base64
const imageBase64 =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
saveFile({
fileName: "image.png",
url: imageBase64,
});API
saveFile(params: TSaveFileParams): void
Saves a file to the user's device.
Parameters
| Parameter | Type | Required | Description |
| ---------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------- |
| url | string | Yes | The URL of the file to save |
| fileName | string | No | The name of the file to be saved. If not provided, the browser will use the original filename from the URL |
How it works
This utility creates a temporary anchor element with the download attribute, triggers a click event, and then removes the element from the DOM. This approach works with:
- Direct file URLs
- Blob URLs
- Data URLs
- Files served with appropriate CORS headers
License
MIT
