在MEAN堆栈上的AWS S3上载

时间:2016-12-18 17:53:44

标签: angularjs node.js heroku amazon-s3

我一直在尝试在我的MEAN堆栈应用following this method中创建一个简单的图像上传到Amazon S3存储桶功能但无法使其工作。

(我正在使用Heroku进行托管)

我在控制台中收到的错误如下: net :: ERR_CONNECTION_TIMED_OUT

节点:

var s3 = {
    bucket: process.env.S3_BUCKET,
    key: process.env.S3_KEY,
    secret: process.env.S3_SECRET,
    url: "https://<my-bucket-name>.s3-us-east-1.amazonaws.com"
}; 

app.post('/api/signing', function(req, res) {

    var request = req.body;
    var fileName = request.filename
    var path = '/avatar' + fileName;

var readType = 'private';

var expiration = moment().add(5, 'm').toDate(); //15 minutes

var s3Policy = {
    'expiration': expiration,
    'conditions': [{
            'bucket': s3.bucket
        },
        ['starts-with', '$key', path], 
        {
            'acl': readType
        },
        {
          'success_action_status': '201'
        },
        ['starts-with', '$Content-Type', request.type],
        ['content-length-range', 2048, 10485760], //min and max
    ]
};

var stringPolicy = JSON.stringify(s3Policy);
var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');

// sign policy
var signature = crypto.createHmac('sha1', s3.secret)
    .update(new Buffer(base64Policy, 'utf-8')).digest('base64');

var credentials = {
    url: s3.url,
    fields: {
        key: path,
        AWSAccessKeyId: s3.key,
        acl: readType,
        policy: base64Policy,
        signature: signature,
        'Content-Type': request.type,
        success_action_status: 201
    }
};
res.send(credentials);
});

角度视图:

myApp.controller('profileController', ['$scope', '$http', '$location', '$route', '$window', '$routeParams', 'Upload', function($scope, $http, $location, $route, $window, $routeParams, Upload){

$scope.onFileSelect = function(files) {

        if (files.length > 0) {
            var filename = files[0].name;
            var type = files[0].type;
            var query = {
                filename: filename,
                type: type
            };

            $http.post('/api/signing', query)
                .success(function(result) {
                    Upload.upload({
                        url: result.url, //s3Url
                        transformRequest: function(data, headersGetter) {
                            var headers = headersGetter();
                            delete headers.Authorization;
                            return data;
                        },
                        fields: result.fields, //credentials
                        method: 'POST',
                        file: files[0]
                    }).progress(function(evt) {
                        console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total));
                    }).success(function(data, status, headers, config) {
                        // file is uploaded successfully
                        console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
                    }).error(function(err) {
                        console.log(err)
                    });
                })
                .error(function(data, status, headers, config) {
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.

                    console.log(data, status, headers, config)
                });
    }
};

}]);

查看(HTML):

<input type="file" ngf-select ngf-change="onFileSelect($files)">

CORS政策

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>http://localhost:3000</AllowedOrigin>
    <AllowedOrigin>http://localhost:5000</AllowedOrigin>
    <AllowedOrigin>http://www.ps101.com/</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 </CORSConfiguration>

1 个答案:

答案 0 :(得分:0)

原来这个修复非常简单。由于我在美国东海岸,将URL简单地更改为:url:&#34; https://.s3.amazonaws.com"解决了这个问题。我相信这是弗吉尼亚州的us-east-1地区的默认值。