Created
October 7, 2021 08:04
-
-
Save SpadarShut/4eaf0da2102554c936882f5c817f10a7 to your computer and use it in GitHub Desktop.
Save file to disk from blob or Response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function saveFileFromResponse(response: Response, filename?: string) { | |
filename = filename || getResponseAttachmentFileName(response) || 'file'; | |
const data = await response.blob(); | |
const type = data.type || 'application/octet-stream'; | |
saveBlobAsFile(data, filename, type) | |
} | |
export function saveBlobAsFile(blob: Blob, fileName: string, mimeType: string){ | |
if (typeof navigator.msSaveBlob === 'function') { | |
navigator.msSaveBlob(blob, fileName); | |
return; | |
} | |
const file = new File([blob], fileName, {type: mimeType}); | |
const exportUrl = URL.createObjectURL(file); | |
window.location.assign(exportUrl); | |
setTimeout(() => { | |
// For Firefox it is necessary to delay revoking the ObjectURL | |
URL.revokeObjectURL(exportUrl); | |
}, 100); | |
} | |
export function getResponseAttachmentFileName(response: Response): string { | |
return response.headers | |
?.get('content-disposition') | |
?.split(';') | |
?.map(str => str.trim()) | |
?.find(str => str.indexOf('filename=') === 0) | |
?.split('filename=')[1] || ''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment