简体   繁体   中英

nodejs uploading to s3 using knox?

for example:

knox.js:

knox.putFile("local.jpeg", "upload.jpeg", {
          "Content-Type": "image/jpeg"
        }, function(err, result) {
          if (err != null) {
            return console.log(err);
          } else {
            return console.log("Uploaded to amazon S3");

I have two images in the same directory as knox.js, local.jpeg and local2.jpeg, i am able to upload local.jpeg to s3, but not local2.jpeg, both files have the same permissions. am i missing anything here? thanks

My implementation without store in locale. With express , knox , mime , fs .

var knox = require('knox').createClient({
    key: S3_KEY,
    secret: S3_SECRET,
    bucket: S3_BUCKET
});

exports.upload = function uploadToAmazon(req, res, next) {
    var file = req.files.file;
    var stream = fs.createReadStream(file.path)
    var mimetype = mime.lookup(file.path);
    var req;

    if (mimetype.localeCompare('image/jpeg')
        || mimetype.localeCompare('image/pjpeg')
        || mimetype.localeCompare('image/png')
        || mimetype.localeCompare('image/gif')) {

        req = knox.putStream(stream, file.name,
            {
                'Content-Type': mimetype,
                'Cache-Control': 'max-age=604800',
                'x-amz-acl': 'public-read',
                'Content-Length': file.size
            },
            function(err, result) {
                console.log(result);
            }
       );
       } else {
        next(new HttpError(HTTPStatus.BAD_REQUEST))
       }

       req.on('response', function(res){
           if (res.statusCode == HTTPStatus.OK) {
               res.json('url: ' + req.url)
           } else {
               next(new HttpError(res.statusCode))
           }
});

That's because your code does not uploade local2.jpeg!

You code will only pushes the file named local.jpeg . You should, for every file, invoke the knox.put() method. I also advise you to have some helper function that will do some string formatting to rename to uploaded file on s3 (or just keep it as it is :) )

var files = ["local.jpeg", "local1.jpeg"];
for (file in files){
  var upload_name = "upload_"+ file; // or whatever you want it to be called

  knox.putFile(file, upload_name, {
         "Content-Type": "image/jpeg"
     }, function (err, result) {
         if (err != null) {
             return console.log(err);
         } else {
             return console.log("Uploaded to amazon S3");
         }
     });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM