在s3亚马逊问题上直接将图像上传到存储桶

时间:2018-06-28 07:16:54

标签: node.js amazon-web-services amazon-s3 aws-sdk multer

我是Amazon s3的新手。我正面临着将图像直接从前端上传到Amazon s3存储桶的问题。

我也看过很多教程,但是没有将图像直接上传到s3的适当说明。他们教我们如何通过本地计算机将图像上传到s3。

我实现了代码,但无法确定如何在不保存到本地计算机的情况下上传图像。

这是我实现的代码,但运气不佳:

s3ImageUpload: (req, res) => {
        var fs = require('fs');
        var multer = require('multer');
        var AWS = require('aws-sdk');
        var path = require('path');

        var awsCredFile = path.join(__dirname, '.', 'key.json');

        console.log('awsCredFile is');
        console.log(awsCredFile);

        AWS.config.loadFromPath(awsCredFile);

        var s3 = new AWS.S3();

        var photoBucket = new AWS.S3({params: {Bucket: 'testbucket'}});

        var sampleFile = {
            //"_id" : 345345,
            //"fieldname" : "uploads[]",
            //"originalname" : "female.JPG",
            //"encoding" : "base64",
            //"mimetype" : "image/jpeg",
            "destination" : "./public/images",
            "filename" : "female.jpeg",
            "path" : "/images/female.jpeg",
            //"size" : 251556,
            //"user" : "579fbe61adac4a8a73b6f508"
        };

        var filePathToSend = path.join(__dirname, '../public', sampleFile.path);


        function uploadToS3(filepath, destFileName, callback) {
            photoBucket
                .upload({
                    ACL: 'public-read',
                    Body: fs.createReadStream(filepath),
                    Key: destFileName.toString(),
                    ContentType: 'image/png'
                })
                // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3/ManagedUpload.html#httpUploadProgress-event
                .on('httpUploadProgress', function(evt) { console.log(evt); })
                // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3/ManagedUpload.html#send-property
                .send(callback);
        }

        multer({limits: {fileSize:10*1024*1024}});

        console.log('filePathToSend is ');
        console.log(filePathToSend);

        uploadToS3(filePathToSend, sampleFile.filename, function (err, data) {
            if (err) {
                console.error(err);
                return res.status(500).send('failed to upload to s3').end();
            }
            res.status(200)
                .send('File uploaded to S3: '
                    + data.Location.replace(/</g, '&lt;')
                    + '<br/><img src="' + data.Location.replace(/"/g, '&quot;') + '"/>')
                .end();
        });

        console.log('uploading now...');
    }

1 个答案:

答案 0 :(得分:0)

预签名URL对您来说可能是一个很好的解决方案。

在您的后端,您可以使用AWS SDK签名URL。然后,您只需要将此URL发送回客户端即可。最后,客户端可以使用此URL上传到文件。

https://docs.aws.amazon.com/AmazonS3/latest/dev/PresignedUrlUploadObject.html