Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Created February 22, 2023 16:53
Show Gist options
  • Save neharkarvishal/37bede35476d5d9463cb5e9bff2cd5d8 to your computer and use it in GitHub Desktop.
Save neharkarvishal/37bede35476d5d9463cb5e9bff2cd5d8 to your computer and use it in GitHub Desktop.
const b64toBlob = (b64Data, contentType = "", sliceSize = 512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
};
export const downloadFile = (data, fileName, isZip) => {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(
b64toBlob(data, "application/pdf"),
fileName
);
} else {
const linkSource = `data:${isZip?`text/plain`:`application/pdf`};base64,${data}`;
const downloadLink = document.createElement("a");
downloadLink.setAttribute("href", linkSource);
downloadLink.setAttribute("download", fileName);
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
return;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment