如何在Node中将图片上传到s3

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

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] 

我是否正确上传文件对象,或者我需要parsing它? 也许我应该使用uploadFile而不是putObject?

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

 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] } 

参考类似的讨论: 上传()和putObject()上传文件到S3的区别?

问题是s3.putObject在上传之前需要知道Body长。 在你的情况下,它不能确定stream的长度(因为它正在stream,从头开始是未知的),所以s3.upload是更合适的。 从文档:

在这里输入图像描述

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