Skip to content

Commit

Permalink
Add downloadBlob
Browse files Browse the repository at this point in the history
  • Loading branch information
AlttiRi committed Sep 8, 2024
1 parent 38e0c98 commit 9dc975f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@alttiri/util-js",
"version": "1.14.0-20240821",
"version": "1.14.1-20240908",
"description": "Some util functions for personal use",
"homepage": "https://github.com/AlttiRi/util-js",
"keywords": [
Expand Down
25 changes: 25 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,28 @@ export function hashString(str: string): number {
}
return hash;
}

export type DownloadBlobOpt = {
/** The URL to be added as a hash in the downloaded blob URL. Useful to keep the original file URL. */
url?: string;
/** The delay before `revokeObjectURL`. 5000 by default. */
timeout?: number;
}
export function downloadBlob(blob: Blob, name: string, url?: string): void;
export function downloadBlob(blob: Blob, name: string, opt: DownloadBlobOpt): void;
export function downloadBlob(blob: Blob, name: string = "", urlOrOpts?: string | DownloadBlobOpt): void {
const anchor = document.createElement("a");
anchor.setAttribute("download", name || "");
const blobUrl = URL.createObjectURL(blob);
let url: string | undefined;
let timeout: number = 5000;
if (isString(urlOrOpts)) {
url = urlOrOpts;
} else {
url = urlOrOpts?.url;
timeout = urlOrOpts?.timeout || timeout;
}
anchor.href = blobUrl + (url ? ("#" + url) : "");
anchor.click();
setTimeout(() => URL.revokeObjectURL(blobUrl), timeout);
}

0 comments on commit 9dc975f

Please sign in to comment.