2012-11-10 112 views
9

例如:nodejs使用knox上传到s3?

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

我在同一个目录中knox.js,local.jpeg和local2.jpeg两个图像,我能够上传local.jpeg到s3,但不是local2.jpeg,这两个文件具有相同的权限。我错过了什么吗?谢谢

回答

-1

这是因为你的代码没有上传local2.jpeg!

您的代码只会推送名为local.jpeg的文件。对于每个文件,您都应该调用knox.put()方法。我也建议你有一些辅助的功能,将做一些字符串格式化重命名为上传的文件上S3(或者只是保持它,因为它是:))

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

我不落实店的语言环境。用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)) 
      } 
}); 
+1

非常有用!谢谢! – CainaSouza

+0

如何指定s3存储桶的文件夹 –

+0

s3完全没有“文件夹”。你只需在“foo/bar /”等文件前加上你的文件,s3控制台就会显示它,就像它在文件夹中一样。在这种情况下,将参数从file.name更改为putStream为“foo /”+ file.name将执行此操作。 – Liam

相关问题