File size: 1,223 Bytes
26c4b30
 
 
 
f665131
5b99fc6
26c4b30
 
 
 
 
6b8f69a
 
26c4b30
 
 
 
 
 
 
 
 
 
 
 
6b8f69a
 
 
 
 
 
 
 
26c4b30
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
import { S3Client } from '@aws-sdk/client-s3';
import { fromEnv } from '@aws-sdk/credential-providers';

const FILE_SIZE_LIMIT = 104857600; // 100MB

const s3Client = new S3Client({
  region: process.env.AWS_REGION,
  credentials: fromEnv(),
});

export const getPresignedUrl = async (fileName: string, fileType: string) => {
  return createPresignedPost(s3Client, {
    Bucket: process.env.AWS_BUCKET_NAME ?? 'vision-agent-dev',
    Key: fileName,
    Conditions: [
      ['content-length-range', 0, FILE_SIZE_LIMIT],
      ['starts-with', '$Content-Type', fileType],
    ],
    Fields: {
      acl: 'public-read',
      'Content-Type': fileType,
    },
    Expires: 600,
  });
};

export const upload = async (
  base64: string,
  fileName: string,
  fileType: string,
) => {
  const { url, fields } = await getPresignedUrl(fileName, fileType);
  const formData = new FormData();
  Object.entries(fields).forEach(([key, value]) => {
    formData.append(key, value as string);
  });
  const res = await fetch(base64);
  const blob = await res.blob();
  formData.append('file', blob);

  return fetch(url, {
    method: 'POST',
    body: formData,
  });
};