Skip to content

Instantly share code, notes, and snippets.

@sriramrudraraju
Created September 14, 2022 21:21
Show Gist options
  • Save sriramrudraraju/126bb174cd8466c5364a5d57d166e44a to your computer and use it in GitHub Desktop.
Save sriramrudraraju/126bb174cd8466c5364a5d57d166e44a to your computer and use it in GitHub Desktop.
File download
export const downloadFile = (blob: Blob, fileName: string) => {
const link = document.createElement("a");
// create a blobURI pointing to our Blob
link.href = URL.createObjectURL(blob);
link.download = fileName;
// some browser needs the anchor to be in the doc
document.body.append(link);
link.click();
link.remove();
// in case the Blob uses a lot of memory
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
};
export const saveAsTextFile = (text: string, fileName: string) => {
const blob = new Blob([text], {
type: "text/plain;charset=utf-8",
});
downloadFile(blob, `${fileName}.txt`);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment