Applicable when
- A file is transferred as a body of API call
- A compressed file is to be unpacked and put to S3
Non-applicable when
- A file is transferred directly to S3 bucket from UI
Implementation
The file content is received base64-encoded in the Lambda. To store it correctly in the S3 bucket, the Buffer object has to be created with the proper encoding and then sent to S3.
The implementation differs if the request contains binary or multipart form-data.
Binary sample
export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> { const bucketName = process.env.BUCKET; if (!bucketName) { throw new Error('Bucket name is missing!'); } if (event.isBase64Encoded) { // binary event.body = Buffer.from(event.body as string, 'base64'); } const s3 = new S3(); const imageKey = uuid(); const params: PutObjectRequest = { Bucket: bucketName, Key: imageKey, ContentType: 'image', Body: event.body }; await s3.putObject(params).promise(); return { statusCode: 200, body: 'success' }; }
Multipart form-data sample
const multipart = require('aws-lambda-multipart-parser'); export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> { const bucketName = process.env.BUCKET; if (!bucketName) { throw new Error('Bucket name is missing!'); } if (event.isBase64Encoded) { // form-data event.body = Buffer.from(event.body as string, 'base64').toString('binary'); } const form = multipart.parse(event, true); const s3 = new S3(); const imageKey = uuid(); const params: PutObjectRequest = { Bucket: bucketName, Key: imageKey, ContentType: 'image', Body: form.image.content }; await s3.putObject(params).promise(); return { statusCode: 200, body: 'success' }; }
Comments
0 comments
Please sign in to leave a comment.