From f47ab2490b815206989c043483ac647b1145da1e Mon Sep 17 00:00:00 2001 From: "Juan Picado @jotadeveloper" Date: Sun, 28 Jul 2019 14:12:18 +0200 Subject: [PATCH] refactor: add download file method --- src/components/ActionBar/ActionBar.tsx | 6 ++++-- src/utils/url.ts | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/components/ActionBar/ActionBar.tsx b/src/components/ActionBar/ActionBar.tsx index 200acaa..8d178e8 100644 --- a/src/components/ActionBar/ActionBar.tsx +++ b/src/components/ActionBar/ActionBar.tsx @@ -8,7 +8,7 @@ import Tooltip from '@material-ui/core/Tooltip'; import { DetailContextConsumer, VersionPageConsumerProps } from '../../pages/version/Version'; import { Fab, ActionListItem } from './styles'; -import { isURL } from '../../utils/url'; +import { isURL, extractFileName, downloadFile } from '../../utils/url'; import api from '../../utils/api'; export interface Action { @@ -18,12 +18,14 @@ export interface Action { } async function downloadHandler(link: string): Promise { - await api.request(link, 'GET', { + const fileStream: Blob = await api.request(link, 'GET', { headers: { ['accept']: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', }, credentials: 'include', }); + const fileName = extractFileName(link); + downloadFile(fileStream, fileName); } const ACTIONS = { diff --git a/src/utils/url.ts b/src/utils/url.ts index d428410..6d63cc7 100644 --- a/src/utils/url.ts +++ b/src/utils/url.ts @@ -18,3 +18,20 @@ export function getRegistryURL(): string { // Don't add slash if it's not a sub directory return `${location.origin}${location.pathname === '/' ? '' : location.pathname}`; } + +export function extractFileName(url: string): string { + return url.substring(url.lastIndexOf('/') + 1); +} + +export function downloadFile(fileStream: Blob, fileName: string): void { + const file = new File([fileStream], fileName, { type: 'application/octet-stream', lastModified: Date.now() }); + const objectURL = URL.createObjectURL(file); + const fileLink = document.createElement('a'); + fileLink.href = objectURL; + fileLink.download = fileName; + fileLink.click(); + // firefox requires remove the object url + setTimeout(() => { + URL.revokeObjectURL(objectURL); + }, 150); +}