We have a S3 bucket where we upload some files.
When a user uploads a file, it is uploaded to the S3 bucket
, but when checking the file's content, it is empty(blank file).
Back End Code
// Importing modules
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
// Setting up S3 client
const s3 = new S3Client({
credentials: {
accessKeyId: process.env.ACCESS_KEY_ID as string,
secretAccessKey: process.env.SECRET_ACCESS_KEY as string,
},
region: s3Info.S3_REGION,
});
const pdfContent = Buffer.from(file[0].buffer);
const params = {
Bucket: s3Info.S3_BUCKET_NAME,
Key: getFilePath(fileName),
Body: pdfContent,
ContentType: file[0].mimetype,
};
// Uploading the document.
const command = new PutObjectCommand(params);
const res = await s3.send(command);
return fileName;
Everything is working fine, but getting blank documents in the S3 bucket.
Since I am using AWS Lambda
and Serverless Framework to deploy.
Now in my serverless.yml file, I was missing a part for Binary media types
.
So without Binary media types
in AWS API Gateway the file was getting uploaded but was blank.
After adding a plugin
called serverless-apigw-binary for my serverless, and then adding apigwBinary types as application/pdf
and multipart/form-data
in my serverless.yml file, it worked.
# Example Serverless.yml code
plugins:
- serverless-apigw-binary
custom:
apigwBinary:
types:
- 'application/pdf'
- 'multipart/form-data'
In API Gateway we can manually also add Media Types as shown in the below image.
Just click on your API Gateway, then select API Settings, and under that, you will see Binary Media Types
.