找不到在AWS S3图像,尽管上传成功 [英] Can't find image in aws s3 despite successful upload

查看:215
本文介绍了找不到在AWS S3图像,尽管上传成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我采用NG-文件上传模块

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

和我的节点后端

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

当我上传,我从我的要求的积极响应。然而,无法找到我的桶的形象。我以为我添加文件名到s3Url的。像

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;

它失败,并返回Forbidden错误结果。我注意到路径变量之上,文件名不应该被追加到s3Url。我尝试了所有我可以没有我的档案不;吨展现在桶。请我在做什么错误是从上传或停止显示该文件?任何帮助将是AP preciated。

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.

推荐答案

如果您通过提交表单文件,那么下面code可以帮助你。

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

不过,我会建议你使用base64en codeR,因为你可以直接把对象从S3的节点服务器,并设置内容类型为文件类型/扩展。
这种Base64编码方法$ P $在大多数的情况下pferrred作为其犯规需要你通过HTTP发送文件。

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.

这篇关于找不到在AWS S3图像,尽管上传成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆