Skip to content

Instantly share code, notes, and snippets.

@SpadarShut
Created October 7, 2021 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpadarShut/4eaf0da2102554c936882f5c817f10a7 to your computer and use it in GitHub Desktop.
Save SpadarShut/4eaf0da2102554c936882f5c817f10a7 to your computer and use it in GitHub Desktop.
Save file to disk from blob or Response
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