将图像上传到s3存储桶节点js

时间:2017-02-15 12:28:35

标签: javascript node.js amazon-web-services amazon-s3

我在将图片从表单上传到我的s3存储桶时遇到了一些问题。目前部分图像上传,例如19kb而不是完整的272kb,如果我尝试从我的桶中打开图像它就会被打破

app.post('/admin/addClub', (req, res) => {
  if (!req.user) {
  res.redirect('/admin');
  return;
}

// Upload image to S3
var s3Bucket = new AWS.S3( { params: {Bucket: process.env.AWS_BUCKET, Key: process.env.AWS_ACCESS_KEY_ID} } )
var data = { Key: req.body.imageBanner, // file from form
             Body: req.body.imageBanner, // Not sure here
             ACL: "public-read",
             ContentType: helper.getContentTypeByFile(req.body.imageBanner)
           };
s3Bucket.putObject(data, function(err, data){
  if (err) 
  { console.log('Error uploading data: ', data); 
    res.redirect('/admin/main');
  } else {
    console.log('succesfully uploaded the image!');
    res.redirect('/admin/main');
  }
});

有人可以建议我需要通过Body密钥吗?因为我认为这一定是我的问题

由于

1 个答案:

答案 0 :(得分:2)

您需要集成express-fileupload包,以便在Express上接收文件上传。

安装run:npm install --save express-fileupload

然后,您需要将req.files.imageBanner.data(假设您的文件上传字段看起来像<input name="imageBanner" type="file" />)作为Body参数传递。以下是它的外观:

var fileUpload = require('express-fileupload');

app.use(fileUpload());

app.post('/admin/addClub', (req, res) => {
  if (!req.user) {
    res.redirect('/admin');
    return;
  }

  // Upload image to S3
  var s3Bucket = new AWS.S3( { params: {Bucket: process.env.AWS_BUCKET, Key: process.env.AWS_ACCESS_KEY_ID} } )
  var data = { Key: req.body.imageBanner, // file from form
               Body: req.files.imageBanner.data,
               ACL: "public-read",
               ContentType: helper.getContentTypeByFile(req.body.imageBanner)
             };
  s3Bucket.putObject(data, function(err, data){
    if (err) 
    { console.log('Error uploading data: ', data); 
      res.redirect('/admin/main');
    } else {
      console.log('succesfully uploaded the image!');
      res.redirect('/admin/main');
    }
  });
});

您可以在此处找到express-fileupload包的文档:

https://www.npmjs.com/package/express-fileupload