正如您的问题的不同评论所示,有几件事可能会引发您的问题。
请确保您提供了有关应被视为二进制的不同内容类型的必要配置。这AWS 文档 https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html提供了有关它的详细信息;这相关SO问题 https://stackoverflow.com/questions/57968048/how-to-upload-image-buffer-data-in-aws-s3也可以很有价值。
由于您正在使用serverless
框架,如链接所示1 https://forum.serverless.com/t/upload-image-to-s3-image-broken/12390 2 https://forum.serverless.com/t/file-uploaded-to-s3-but-it-doesnt-open-corrupted/11018您引用的,请同时提供必要的配置:
provider:
apiGateway:
binaryMediaTypes:
- 'multipart/form-data'
无论如何,即使使用此配置,您仍然面临问题。您告诉您能够成功上传文本文件,但是您的图像被损坏,增加了它们的大小:如评论中所示,这似乎清楚地表明在某些地方信息正在转换为不同的编码,从二进制到文本,类似的东西。事实上,根据您的依赖关系,这似乎是实际问题,如报告中所述这个问题 https://github.com/dougmoscrop/serverless-http/issues/81 of the serverless-http
图书馆,尤其是在其他方面1 https://github.com/dherault/serverless-offline/issues/464 and 2 https://github.com/dherault/serverless-offline/pull/784 of the serverless-offline
图书馆。
我认为这个问题只是本地的,并且它可能会在 AWS 中正常运行而不会出现更多问题。
无论如何,正如您在上述问题的第一个问题中看到的,与serverless-http
,该库有以下代码:
return Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8');
因此,作为一种解决方法,以 Base 64 编码形式提交信息可以解决该问题:如果您在 HTML 中使用表单提交,那么这不是一个简单的任务 - 例如请参阅此很好的例子 https://formcarry.com/blog/how-to-upload-files-as-base64/对于一些想法 - 尽管如果您通过代码直接与 API 交互,它也可以解决问题。唯一需要的更改是您的 params 变量:
const params = {
Bucket: process.env.AWS_S3_BUCKET,
Key: folderName+'/'+filename,
Body: Buffer.from(data.data, 'base64'),
ContentEncoding: 'base64',
ContentType: 'image/jpeg',
ACL:'public-read',
};
请注意使用Buffer.from(..., 'base64')
以及纳入ContentEncoding: 'base64'
.
无论如何,如果代码可以在 AWS 中运行,我认为最好的方法就是等待serverless-offline
问题解决。