如何将图片上传到节点

时间:2017-04-17 21:55:03

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

从我的反应前端向节点后端发布文件。

request
.post('/api/upload')
.field('fileName', res.body.text)
.field('filePath', `/${this.s3DirName}`) // set dynamically
.attach('file', data.file)
.end((err2, res2) => {
    if (err2){ 
        console.log('err2', err2);
        this.setState({ error: true, sending: false, success: true });
    }else{
        console.log('res2', res2);
        this.setState({ error: false, sending: false, success: true });
    }

});

然后在我的节点后端我想上传到s3。我正在使用busboy来获取已发布的多部分文件,然后将aws sdk发送到我的s3存储桶。

var AWS = require('aws-sdk');

const s3 = new AWS.S3({
  apiVersion: '2006-03-01',
  params: {Bucket: 'bucketName'}
});

static upload(req, res) {

    req.pipe(req.busboy);

    req.busboy.on('file', (fieldname, file, filename) => {
      console.log("Uploading: " + filename);
      console.log("file: ", file);

      var params = {
        Bucket: 'bucketName',
        Key: filename,
        Body: file
      };

      s3.putObject(params, function (perr, pres) {
        if (perr) {
          console.log("Error uploading data: ", perr);
          res.send('err')
        } else {
          console.log("Successfully uploaded data to myBucket/myKey");
          res.send('success')
        }
      });

    });

}

但我收到错误

Error uploading data:  { Error: Cannot determine length of [object Object]

我是直接上传文件对象还是我需要解析它?也许我应该使用uploadFile而不是putObject?

如果有帮助,这是我的console.logs的输出,我记录文件和文件名

Uploading: 31032017919Chairs.jpg
file:  FileStream {
  _readableState: 
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: { end: [Function] },
  _eventsCount: 1,
  _maxListeners: undefined,
  truncated: false,
  _read: [Function] }

1 个答案:

答案 0 :(得分:10)

参考类似的讨论:Difference between upload() and putObject() for uploading a file to S3?

问题是s3.putObject在上传之前需要知道Body长度。在您的情况下,它无法确定流的长度(因为它正在流式传输,从一开始就不知道),因此s3.upload更合适。来自文档:

enter image description here

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property