我正在尝试使用NestJS API上的multer-s3将图像上传到AWS s3。我也尝试过aws-sdk。我使用FileInterceptor和UploadedFile装饰器捕获文件请求。到目前为止,我所拥有的是:
id status days_until_approve transaction_ids_not_approved total_transaction_ids
1 approved 21 25,33 3
2 approved None 25 2
这给了我以下错误:
// Controller
@Post()
@UseInterceptors(FileInterceptor('file', multerOptions))
uploadImage(@UploadedFile() file) {
console.log(file);
}
// multerOptions. 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
}),
};
有什么主意吗?谢谢。
答案 0 :(得分:7)
您可以创建一个类似
的控制器import { Post, UseInterceptors, UploadedFile } from '@nestjs/common';
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
async upload(@UploadedFile() file) {
return await this.service.upload(file);
}
您的服务应该像
import { S3 } from 'aws-sdk';
import { Logger } from '@nestjs/common';
async upload(file) {
const { originalname } = file;
const bucketS3 = 'my-aws-bucket';
await this.uploadS3(file.buffer, bucketS3, originalname);
}
async uploadS3(file, bucket, name) {
const s3 = this.getS3();
const params = {
Bucket: bucket,
Key: String(name),
Body: file,
};
return new Promise((resolve, reject) => {
s3.upload(params, (err, data) => {
if (err) {
Logger.error(err);
reject(err.message);
}
resolve(data);
});
});
}
getS3() {
return new S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
}
希望我能为您提供帮助。