我们有一个 S3 存储桶,用于上传一些文件。
当用户上传文件时,它被上传到
S3 bucket
,但是当检查文件内容时,它是空(空白文件)。
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;
一切正常,但 S3 存储桶中出现空白文档。
因为我使用
AWS Lambda
和 Serverless Framework 来部署。
现在在我的 serverless.yml 文件中,我缺少
Binary media types
的一部分。
因此,如果
AWS API Gateway中没有
Binary media types
,文件已上传但为空。
为我的无服务器添加一个名为
serverless-apigw-binary的
plugin
,然后在我的serverless.yml文件中添加apigwBinary类型作为application/pdf
和multipart/form-data
,它起作用了。
# Example Serverless.yml code
plugins:
- serverless-apigw-binary
custom:
apigwBinary:
types:
- 'application/pdf'
- 'multipart/form-data'
在 API Gateway 中,我们还可以手动添加媒体类型,如下图所示。 只需单击您的 API 网关,然后选择 API 设置,在其下方,您将看到
Binary Media Types
。