问题描述
将文件从我的React前端发布到节点后端.
Posting a file from my react front end to the node back end.
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存储桶.
and then on my node backend I want to upload to s3. I am using busboy to be able to get the multipart file that is posted and then the aws sdk to send to my s3 bucket.
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?
Am I correct in uploading the file object directly or do I need to parse it? Perhaps I should be using uploadFile instead of putObject?
如果有帮助,这是我console.logs的输出,我在其中记录文件和文件名
If it helps, this is the output of my console.logs where I log the file and file name
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] }
推荐答案
请参阅类似的讨论:
问题是s3.putObject
需要在上传前知道Body
长度.在您的情况下,它无法确定流的长度(因为正在流式传输,因此从一开始就未知),因此s3.upload
更合适.从文档中:
The problem is s3.putObject
needs to know Body
length before upload. In your case, it cannot determine length of the stream (because it's being streamed, it's unknown from the beginning), so s3.upload
is more suitable. From the docs:
http://docs.aws.amazon. com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property
这篇关于如何在Node中将图像上传到s3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!