3

I used connect-multiparty middlewhere and I have below code:

console.log(req.files)

      var data = {
        Key: req.body.filename,
        Body: req.files,
        ContentType: 'image/jpeg'
      };


      s3Bucket.putObject(data,function(err,result){
        console.log(err);
      });

And I got below result in my terminal:

{ photo: 
   { fieldName: 'photo',
     originalFilename: 'blob',
     path: '/var/folders/n1/fr69rt5j01sfwjhsh3jx3gh00000gn/T/Tw4pwoPQ5D7zCGxrk3U1ywKp',
     headers: 
      { 'content-disposition': 'form-data; name="photo"; filename="blob"',
        'content-type': 'image/jpeg' },
     size: 50138,
     name: 'blob',
     type: 'image/jpeg' } }
{ [InvalidParameterType: Expected params.Body to be a string, Buffer, Stream, Blob, or typed array object]
  message: 'Expected params.Body to be a string, Buffer, Stream, Blob, or typed array object',
  code: 'InvalidParameterType',

Any clue this doesn't work? What should be Body's value?

2 Answers 2

6

If you have base64 format of image you can use below method.

The parameters to this is

1.image : base64 format of image

2.FileName : name of the file in string Eg: 'name.jpg'

var UploadFilesToS3 = function(image,FileName) {  //
    buf = new Buffer(image.replace(/^data:image\/\w+;base64,/, ""),'base64');
    var data = {
        Key: FileName,
        Body: buf,
        ContentEncoding: 'base64',
        ContentType: 'image/jpeg'
    };
    s3Bucket.putObject(data,function (data,err){
        if(err)
        {
            console.log('failed to Upload: '+ err.body);
        }
    });
};

And also you need to make AWS configuration before calling this method like this

var AWS = require('aws-sdk');
AWS.config.update({
        accessKeyId: '',
        secretAccessKey: '',
        region: ''
    });

var s3Bucket = new AWS.S3( { params: {Bucket: 'name of the bucket'} } );
Sign up to request clarification or add additional context in comments.

3 Comments

where is the image come from?
Image is the photo that you need to upload
Great answer. Do you know why we have to convert it to a buffer and we can't just upload it as a string? I believe the AWS putObject method accepts body as a string, Buffer, Stream, Blob, or typed array object.
0

The req.files is not the thing you need to upload, try this:

var fs = require('fs')
var photo = req.files.photo
var data = {
  Key: req.body.filename,
  Body: fs.createReadStream(photo.path),
  ContentType: photo.type
};

s3Bucket.putObject(data, function (err, result) {
  if (err) console.error(err);
  else console.log(result);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.