当前位置: 动力学知识库 > 问答 > 编程问答 >

amazon web services - aws-sdk node.js s3 putObject from request body

问题描述:

I'm trying to save a PDF into S3 with the AWS-SDK.

I'm getting the PDF through the body of a POST (Application/PDF).

When saving the file into the local HD with fs.writeFile the file look OK.

But when uploading into s3 the file is corrupted (single white page pdf)

Any help or hint would be greatly appreciated!

var data = body // body from a POST request.

var fileName = "test.pdf";

fs.writeFile(fileName, data, {encoding : "binary"}, function(err, data) {

console.log('saved'); // File is OK!

});

s3.putObject({ Bucket: "bucketName", Key: fileName, Body: data }, function(err, data) {

console.log('uploaded') // File uploads incorrectly.

});

EDIT:

It works if I write and then read the file and then upload it.

fs.writeFile(fileName, data, {encoding : "binary"}, function(err, data) {

fs.readFile(fileName, function(err, fileData) {

s3.putObject({ Bucket: "bucketName", Key: fileName, Body: fileData }, function(err, data) {

console.log('uploaded') // File uploads correctly.

});

});

});

网友答案:

Try setting the contentType and/or ContentEncoding on your put to S3.

 ContentType: 'binary', ContentEncoding: 'utf8'

See the code sample here for working example putObject makes object larger on server in Nodejs

网友答案:

I think it is because the data is consumed (i.e. a stream).

It would explain why after writting the data you send nothing to S3 and reading again the data you can send a valid PDF.

Try and see if it works by just sending the data directly to S3 without writting it to disk.

网友答案:

Yes, you forgot about callback of writeFile function, so when you started uploading to Amazon S3 your file wasn't saved completly. You shouldn't forget that node.js is asynchronous and an app won't wait when the fs.writeFile finishes it work, it simply run s3.putObject the same time.

分享给朋友:
您可能感兴趣的文章:
随机阅读: