Skip to content

Instantly share code, notes, and snippets.

@railsstudent
Last active June 16, 2020 03:54
Show Gist options
  • Save railsstudent/f4456ad0a4c5e82b42d8a639d2d20535 to your computer and use it in GitHub Desktop.
Save railsstudent/f4456ad0a4c5e82b42d8a639d2d20535 to your computer and use it in GitHub Desktop.
use file-saver to open file
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