-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathuse-presigned-upload.ts
45 lines (36 loc) · 1.06 KB
/
use-presigned-upload.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { Uploader, useUploader } from './use-uploader';
let upload: Uploader = async (file, params, { onProgress }) => {
let { url, key, bucket, region, endpoint } = params;
let buffer = await file.arrayBuffer();
await new Promise<void>((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.upload.onprogress = (event: ProgressEvent) => {
onProgress(event.loaded);
};
xhr.open('PUT', url, true);
xhr.setRequestHeader('Content-Type', file.type);
xhr.setRequestHeader('Cache-Control', 'max-age=630720000');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
} else {
reject();
}
}
};
xhr.send(buffer);
});
let resultUrl = endpoint
? `${endpoint}/${bucket}/${key}`
: `https://${bucket}.s3.${region}.amazonaws.com/${key}`;
return {
url: resultUrl,
bucket,
key,
};
};
export const usePresignedUpload = () => {
let hook = useUploader('presigned', upload);
return hook;
};