1
0
Fork 1
mirror of https://github.com/SomboChea/ui synced 2024-06-18 17:29:43 +07:00

refactor: add download file method

This commit is contained in:
Juan Picado @jotadeveloper 2019-07-28 14:12:18 +02:00
parent 83b6a9d247
commit f47ab2490b
No known key found for this signature in database
GPG Key ID: 15AA875EF3768142
2 changed files with 21 additions and 2 deletions

View File

@ -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<void> {
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 = {

View File

@ -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);
}