From 5f6a4724cc7280e1fc08d3bb2e7eb4b46db6d7bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A4=D1=80=D0=BE=D0=BB=D0=BE=D0=B2?= Date: Tue, 17 Aug 2021 10:46:10 +0500 Subject: [PATCH] Add download function --- src/components/factory.ts | 43 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/components/factory.ts b/src/components/factory.ts index b6e7aa3..000700f 100644 --- a/src/components/factory.ts +++ b/src/components/factory.ts @@ -69,7 +69,7 @@ export const makePaginationObject = (paginationContainer:PaginationContainer, .. } } -export const updateFromWebApiWrapperAsync = async (funcAsync: asyncFunction, setShowLoader: Dispatch>, errorNotifyText: string) => { +export const updateFromWebApiWrapperAsync = async (funcAsync: asyncFunction, setShowLoader: Dispatch>, errorNotifyText: string) => { if(setShowLoader) setShowLoader(true) try{ @@ -83,4 +83,45 @@ export const updateFromWebApiWrapperAsync = async (funcAsync: asyncFunction, set if(setShowLoader) setShowLoader(false) } +} + +export const download = async (url:string, fileName?:string) => { + const response = await fetch(url, { + headers: { + Authorization: 'Bearer ' + localStorage['token'] + }, + method: 'Get' + }) + const requestFileName = decodeURI(fileName + ??response.headers + .get('content-disposition') + ?.split(';') + .splice(-1)[0] + .split("'") + .splice(-1)[0] + ?? url.replace('\\','/') + .split('/') + .splice(-1)[0] + ?? 'file') + const blob = await response.blob() + const reader = new FileReader(); + reader.readAsDataURL(blob); + reader.onload = function (e) { + let a = document.createElement('a'); + a.href = (e.target?.result?.toString() ?? ''); + a.download = requestFileName; + document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox + a.click(); + a.remove(); + }; +} + +export const upload = async (url:string, formData: FormData) => { + await fetch(url, { + headers: { + Authorization: 'Bearer ' + localStorage['token'] + }, + method: 'Post', + body: formData, + }) } \ No newline at end of file