我在需要將圖像文件上傳到Amazon S3的MEAN(MongoDB,Express,AngularJS,node.js)堆棧上構建應用程序。我按照以下方式執行:從AngularJS發佈到Amazon S3時發生錯誤
首先,將http get
發送到我的API,該API指定交互的「策略文檔」並將其返回到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速記和刪除「內容類型」:「多/表單數據」規範,像這樣的:
$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
我已經試過的,我能想到的條件和規定的任意組合。我在這裏錯過了什麼?
可能相關:http://stackoverflow.com/questions/23098223 /上傳-FORMDATA-從觸發-IO-鍛造到亞馬遜-S3 –