From 0d84b5161170baf6fc2353f3f8e850aae036bf52 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Wed, 19 Aug 2020 19:32:02 +0300 Subject: feat: add image compression --- src/hooks/useS3Preupload.tsx | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) (limited to 'src/hooks/useS3Preupload.tsx') diff --git a/src/hooks/useS3Preupload.tsx b/src/hooks/useS3Preupload.tsx index 1fb2cd6..22f2513 100644 --- a/src/hooks/useS3Preupload.tsx +++ b/src/hooks/useS3Preupload.tsx @@ -1,5 +1,7 @@ import { useState, useCallback, useMemo } from 'react'; import axios from 'axios'; +import Bluebird from 'bluebird'; +import Compressor from 'compressorjs'; import { get } from '../requests'; @@ -15,6 +17,18 @@ interface Hook { progress: number; } + +const compressFile = (file: File, quality = 0.6): Promise => { + return new Promise((resolve, reject) => { + // eslint-disable-next-line no-new + new Compressor(file, { + success: result => resolve(result), + error: err => reject(err), + quality, + }); + }); +}; + export default (): Hook => { const [url, setUrl] = useState(); const [file, setFile] = useState(); @@ -37,7 +51,7 @@ export default (): Hook => { setProgress(Math.round((progressEvent.loaded * 95) / progressEvent.total)); }, [setProgress]); - const resolve = useCallback(async (): Promise => { + const resolve = useCallback(async (quality?: number): Promise => { if (file) { const config = { headers: { 'Content-Type': 'image/png' }, @@ -45,11 +59,14 @@ export default (): Hook => { }; setProgress(0.01); + // Add querystring to avoid caching request in some browsers, see // https://stackoverflow.com/questions/59339561/safari-skipping-xmlhttprequests - return get(`/files?key=${file.name}`) - .then(response => response.data) - .then(uploadUrl => axios.put(uploadUrl, file, config)) + return Bluebird.all([get(`/files?key=${file.name}`), compressFile(file, quality)]) + .then(([response, compressedFile]) => { + const uploadUrl = response.data; + return axios.put(uploadUrl, compressedFile, config); + }) .then(response => { setProgress(100); const uri = response.config.url; -- cgit v1.2.3