aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/useS3Preupload.tsx
diff options
context:
space:
mode:
authoreug-vs <eug-vs@keemail.me>2020-08-19 19:32:02 +0300
committereug-vs <eug-vs@keemail.me>2020-08-19 19:32:02 +0300
commit0d84b5161170baf6fc2353f3f8e850aae036bf52 (patch)
treeec90e2a7ea9621f0e958f03f914a08992d931f1b /src/hooks/useS3Preupload.tsx
parent71d312f4130b007ad19485ce2126750ff81ea5e4 (diff)
downloadwhich-ui-0d84b5161170baf6fc2353f3f8e850aae036bf52.tar.gz
feat: add image compression
Diffstat (limited to 'src/hooks/useS3Preupload.tsx')
-rw-r--r--src/hooks/useS3Preupload.tsx25
1 files changed, 21 insertions, 4 deletions
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<Blob> => {
+ 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<string>();
const [file, setFile] = useState<File>();
@@ -37,7 +51,7 @@ export default (): Hook => {
setProgress(Math.round((progressEvent.loaded * 95) / progressEvent.total));
}, [setProgress]);
- const resolve = useCallback(async (): Promise<string> => {
+ const resolve = useCallback(async (quality?: number): Promise<string> => {
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;