我正在 MEAN(MongoDB、Express、AngularJS、node.js)堆栈上构建一个应用程序,该应用程序需要将图像文件上传到 Amazon S3。我正在通过以下方式进行操作:
首先,向我的 API 发送一个 http get
,它指定交互的“策略文档”并将其返回给 AngularJS 前端。该后端代码如下所示(填充了变量):
exports.S3Signing = function(req, res) {
var bucket = "MY_BUCKET_NAME",
awsKey = "MY_AWS_KEY",
secret = "MY_SECRET",
fileName = req.params.userId,
expiration = new Date(new Date().getTime() + 1000 * 60 * 5).toISOString();
var policy = {
"expiration": expiration,
"conditions": [
{"bucket": bucket},
{"key": fileName},
{"acl": 'public-read'},
["starts-with", "$Content-Type", ""],
["content-length-range", 0, 524288000]
]};
policyBase64 = new Buffer(JSON.stringify(policy), 'utf8').toString('base64');
signature = crypto.createHmac('sha1', secret).update(policyBase64).digest('base64');
res.json({bucket: bucket, awsKey: awsKey, policy: policyBase64, signature: signature});
};
此过程的前端 (AngularJS) 代码如下所示:
$http.get('/api/v1/auth/signS3/' + userId).success(function(data, status) {
var formData = new FormData();
formData.append('key', userId);
formData.append('AWSAccessKeyId', data.awsKey);
formData.append('acl', 'public-read');
formData.append('policy', data.policy);
formData.append('signature', data.signature);
formData.append('Content-Type', image.type);
formData.append('file', image);
$http({
method: 'POST',
url: 'http://' + data.bucket + '.s3.amazonaws.com/',
headers: {'Content-Type': 'multipart/form-data'},
data: formData
}).success(function(data) {
deferred.resolve(data);
}).error(function(err) {
deferred.reject(err);
});
}).error(function(err, status) {
deferred.reject(err);
});
但是,就目前而言,如果我发布图片,我会收到以下错误:
Malformed POST Request The body of your POST request is not well-formed multipart/form-data.
如果我将 http POST 调用更改为 AngularJS 速记并删除 "content-type": "multipart/form-data" 规范,如下所示:
$http.post('http://' + data.bucket + '.s3.amazonaws.com/', formData).success(function(data) {
deferred.resolve(data);
}).error(function(err) {
deferred.reject(err);
});
我收到以下错误:
Precondition Failed At least one of the pre-conditions you specified did not hold Bucket POST must be of the enclosure-type multipart/form-data
我已经尝试了我能想到的任何条件和规范的组合。我在这里想念什么?