@giapspzoo/save-file
v2.0.0
Published
A TypeScript utility for saving files in the browser.
Downloads
32
Readme
@giapspzoo/save-file
A TypeScript utility for saving files in the browser.
Installation
This package is browser-only — it requires document and the DOM download APIs. It will not work in Node.js or SSR environments.
npm install @giapspzoo/save-fileUsage
import { saveFile, saveBlobFile } 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 = saveBlobFile({
fileName: "hello.txt",
blob,
});
// Revoke when the browser no longer needs the URL (see note below)
URL.revokeObjectURL(blobUrl);
// 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 |
saveBlobFile(params: TSaveBlobFileParams): string
Saves a Blob to the user's device. Creates a temporary object URL, triggers the download, and returns that URL so you can revoke it when appropriate.
Parameters
| Parameter | Type | Required | Description |
| ---------- | -------- | -------- | -------------------------------- |
| blob | Blob | Yes | The blob data to save |
| fileName | string | No | The name of the file to be saved |
Blob URL cleanup
saveBlobFile does not revoke the object URL automatically. Call URL.revokeObjectURL(url) when the browser has finished reading it — otherwise the blob stays in memory.
There is no standard event for “download started,” so wait long enough for the download to begin before revoking. Revoking too early can cause silent download failures in some browsers.
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
