【发布时间】:2020-08-22 15:26:43
【问题描述】:
我正在尝试使用可以接受二进制输入并将数据存储在 S3 中的无服务器框架编写文件上传服务。
问题是文件最终在 S3 存储桶中损坏。文本文件可以通过,但我的测试图像没有。
这是我目前的代码:
const serverless = require('serverless-http');
const express = require('express');
const crypto = require("crypto")
const AWS = require('aws-sdk');
const app = express();
const s3 = new AWS.S3();
app.use(function(req, res, next) {
var chunks = [];
req.on('data', function(chunk) { chunks.push(chunk); });
req.on('end', function() {
req.rawBody = Buffer.concat(chunks);
next();
});
});
app.put('/v1/upload', async (req, res, cb) => {
let hash = crypto.createHash("sha256").update(req.rawBody).digest("hex");
console.log(req.rawBody.length);
... s3 stuff here
我可以在控制台看到文件大小错误; 2540872。实际大小为1395559。 我正在使用 curl 来测试上传
curl -v -X PUT -H "Content-Type: application/octet-stream" --data-binary @test/image.png http://localhost:3000/prod/v1/upload
【问题讨论】:
-
当您创建 lambda 时,AWS 自动为您创建了一个 API 网关。转到 API Gateway 设置并添加
*/*以被视为二进制文件。那应该可以解决您的问题。如果没有,请在不设置任何内容类型的情况下执行您的 PUT 请求。 (除了*/*) Obs:@gareth-mccumskey 回复可能是正确的方法,但这是针对具体问题的解决方案。
标签: node.js upload binary serverless-framework