Last active
June 16, 2020 03:54
-
-
Save railsstudent/f4456ad0a4c5e82b42d8a639d2d20535 to your computer and use it in GitHub Desktop.
use file-saver to open file
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
import { saveAs } from 'file-saver' | |
interface FileDownloadResponse<T> { | |
body: T | null; | |
contentDisposition: string; | |
contentType: string; | |
} | |
private getFileNameFromContentDisposition(res: FileDownloadResponse<Blob>) { | |
const { contentDisposition } = res; | |
const matches = /filename=([^;]+)/gi.exec(contentDisposition); | |
const tempFilename = ((matches && matches[1]) || 'untitled').trim(); | |
const filename = tempFilename.replace(/["]/g, ''); | |
return filename; | |
} | |
openFile(response: FileDownloadResponse<Blob>) { | |
if (response && response.body) { | |
const { contentType } = response; | |
const filename = this.getFileNameFromContentDisposition(response); | |
saveAs(new Blob([response.body], { type: contentType }), filename); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment