Can't find image in aws s3 despite successful upload

左心房为你撑大大i 提交于 2020-01-06 03:07:01

问题


I am utilising ng-file-upload module

<?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>

I found similar question Here. My angular front end is exactly from the two links above that is.

 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.
        });
    };
}]);

And my node backend

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);
});

When i upload , i get a positive response from my request . Yet cant find the image in my bucket. I thought of adding my fileNAme to the s3Url. like

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

It fails and return forbidden error as a result. I noticed with path variable above, the file name should not be appended to the s3Url. I tried all i could yet my file don;t show in the bucket. Please what i am doing wrong that is stopping the file from uploading or showing ?Any help would be appreciated.


回答1:


If you are submitting file through form then following code might help you.

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);
            }
        });
    });
};

But i would suggest you to use base64encoder because you can directly put a object in s3 from your node server and set the content type as the file type/extension. This Base64 approach is preferrred in most of the case as its doesnt need you to send files over http.



来源:https://stackoverflow.com/questions/36549765/cant-find-image-in-aws-s3-despite-successful-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!