尽管上传成功,但无法在aws s3中找到图像

时间:2016-04-11 13:13:19

标签: javascript angularjs node.js amazon-s3

我正在使用ng-file-upload模块

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

我发现了类似的问题Here。我的角度前端完全来自上面的两个链接。

 App.controller('MyCtrl2', ['$scope', '$http', 'Upload', '$timeout', function ($scope, $http, Upload, $timeout) {
    $scope.uploadPic = function(file) {
        var filename = file.name;
        var type = file.type;
        var query = {
            filename: filename,
            type: type
        };
        $http.post('/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: file
                }).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() {

                });
            })
            .error(function(data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
        });
    };
}]);

我的节点后端

app.post('/signing', function(req, res) {
    var request = req.body;
    var fileName = request.filename
    var s3Url = 'https://' + aws.bucket + '.s3' +  '.amazonaws.com/';
    var extension = fileName.substring(fileName.lastIndexOf('.'));
    var today = new Date();
    var path = '/' + today.getFullYear() + '/' + today.getMonth() + '/' + today.getDate() + '/' + uuid.v4() + extension;

    var readType = 'private';

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

    var s3Policy = {
        'expiration': expiration,
        'conditions': [{
                'bucket': aws.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', aws.secret)
        .update(new Buffer(base64Policy, 'utf-8')).digest('base64');

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

当我上传时,我得到了我的请求的积极回应。然而,在我的桶里找不到图像。我想把我的fileNAme添加到s3Url。喜欢

var s3Url = 'https://' + aws.bucket + '.s3' +  '.amazonaws.com/' + fileName;

失败并返回禁止的错误。我注意到上面有path变量,文件名不应该附加到s3Url。我尽力了,但我的文件还没有;显示在桶中。请问我做错了什么是阻止文件上传或显示?任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果您通过表单提交文件,则以下代码可能会对您有所帮助。

exports.uploadImageToS3Bucket = function(res, file, folder, callback) {
    var fs = require('node-fs');
    var AWS = require('aws-sdk');


    var filename = file.name; // actual filename of file
    var path = file.path; //will be put into a temp directory
    var mimeType = file.type;

    var accessKeyId = config.get('s3BucketCredentials.accessKeyId');
    var secretAccessKeyId = config.get('s3BucketCredentials.secretAccessKey');
    var bucketName = config.get('s3BucketCredentials.bucket');

    var timestamp = new Date().getTime().toString();
    var str = '';
    var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var size = chars.length;
    for (var i = 0; i < 5; i++) {
        var randomnumber = Math.floor(Math.random() * size);
        str = chars[randomnumber] + str;
    }
    filename = filename.replace(/\s/g, '');
    var fileNewName = str + timestamp + "-" + filename;

    fs.readFile(path, function(error, file_buffer) {
        if (error) {
            responses.imageUploadError(res,{});
        }
        AWS.config.update({accessKeyId: accessKeyId, secretAccessKey: secretAccessKeyId});
        var s3bucket = new AWS.S3();


        var params = {Bucket: bucketName, Key: folder + '/' + fileNewName, Body: file_buffer, ACL: 'public-read', ContentType: mimeType};
        s3bucket.putObject(params, function(err, data) {
            if (err) {
                console.log(err);
                responses.imageUploadError(res,{});
            } else {
                return callback(fileNewName);
            }
        });
    });
};

但我建议您使用base64encoder,因为您可以直接从节点服务器将对象放入s3,并将内容类型设置为文件类型/扩展名。 在大多数情况下,这种Base64方法更受欢迎,因为它不需要您通过http发送文件。