vision-agent / lib /aws.ts
wuyiqun0718's picture
feat: support upload to aws s3 and save to kv store
26c4b30
raw
history blame
1.15 kB
import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
import { S3Client } from '@aws-sdk/client-s3';
import { fromEnv } from '@aws-sdk/credential-providers';
const s3Client = new S3Client({
region: process.env.AWS_REGION,
credentials: fromEnv(),
});
const FILE_SIZE_LIMIT = 10485760; // 10MB
export const upload = async (
base64: string,
fileName: string,
fileType: string,
) => {
const imageBuffer = Buffer.from(base64, 'base64');
const { url, fields } = await 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,
});
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,
});
};