I'm currently working on implementing an image upload feature to AWS S3 using multer-s3 within my NestJS API. I have experimented with aws-sdk as well. I am utilizing FileInterceptor and UploadedFile decorator to handle the file request. This is what I have achieved so far:
// Controller
@Post()
@UseInterceptors(FileInterceptor('file', multerOptions))
uploadImage(@UploadedFile() file) {
console.log(file);
}
// multerOptions in multer.ts file
const configService = new ConfigService();
export const accessParams = {
accessKeyId: configService.get('AWS_ACCESS_KEY_ID'),
secretAccessKey: configService.get('AWS_SECRET_ACCESS_KEY'),
region: configService.get('AWS_REGION'),
};
const imageMimeTypes = [
'image/jpg',
'image/jpeg',
'image/png',
'image/bmp',
];
AWS.config.update(accessParams);
export const s3 = new AWS.S3();
export const multerOptions = {
fileFilter: (req: any, file: any, cb: any) => {
const mimeType = imageMimeTypes.find(im => im === file.mimetype);
if (mimeType) {
cb(null, true);
} else {
cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);
}
},
storage: multerS3({
s3: s3,
bucket: configService.get('S3_BUCKET_NAME'),
acl: 'read-public',
metadata: function (req, file, cb) {
cb(null, { fieldName: file.fieldname })
},
key: (req: any, file: any, cb: any) => {
cb(null, `${Date.now().toString()}/${file.originalname}`);
},
contentType: multerS3.AUTO_CONTENT_TYPE
}),
};
However, this implementation results in the following error being triggered:
{
"message": null,
"code": "InvalidArgument",
"region": null,
"time": "2020-04-24T05:34:19.009Z",
"requestId": "DH224C558HTDF8E3",
"extendedRequestId": "JKHKJH6877-LKJALDNC765llLKAL=",
"statusCode": 400,
"retryable": false,
"retryDelay": 6.790294010827713,
"storageErrors": []
}
Would appreciate any insights or suggestions to resolve this issue. Thank you.