cassmtnr
cassmtnr

Reputation: 947

Uploading image to Amazon S3 with Node.js results in a small transparent square

I am uploading a image to Amazon S3 bucket but when it arrives there, it's a small transparent square, in the future I will use a Front-end application and the file will be uploaded from user computer.

I am using an ReGex for transforming to base64, but when it arrives at the S3 Bucket it is a small square as you can see here:

https://s3.amazonaws.com/node-str-img-bucket/v0u2HHYolOYwXprSeU73v.jpg

My original file URL that I am using for testing upload you can see clicking here.

Here is my JavaScript uploading process:

AWS.config.update(config.AWS);
const s3 = new AWS.S3();
const bucket = 'node-str-img-bucket';

let filename = nanoid().toString() + '.jpg';
let rawdata = req.body.image;
let matches = rawdata.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
let type = matches[1];
let buffer = new Buffer(matches[2], 'base64');

let params = {
    Bucket: bucket,
    Key: filename,
    Body: rawdata,
    ContentType: type,
    ACL: 'public-read'
};

await s3.upload(params, (error, data) => {
    if (error) {
        console.log(error);
    } else {
        console.log(data);
    }
});

Anything you can help me would be nice.

Upvotes: 1

Views: 3990

Answers (3)

Jacky Raichand
Jacky Raichand

Reputation: 39

req.files[0] will have following data

{ fieldname: 'img', originalname: 'Annotation 2021-01-11 095535.png', encoding: '7bit', mimetype: 'image/png', buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 2d 00 00 01 a2 08 06 00 00 00 9b 3e 85 60 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 04 ... 38012 more bytes>, size: 38062 }

now try this -

const { originalname, buffer, encoding, mimetype } = req.files[0]
s3.upload ({Bucket: 'somebucket',
        Key: originalname, 
        Body: buffer,
        ContentEncoding: encoding,
        ContentType: mimetype,
    },function (err, data) {
    if (err) {
       console.log("Error", err);
     } if (data) {
       console.log("Upload Success", data.Location);
     }
   })

Upvotes: 1

Ghamgui Khaled
Ghamgui Khaled

Reputation: 434

Had the same issues and tried to solve it for hours. Seems like the problem is coming from the API Gateway configuration. If you are using the console,go to the settings and add to the Binary Media Types */* or using open api add x-amazon-apigateway-binary-media-types: [ "/" ]` at the top of the file

Upvotes: 1

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

use putObject rather than upload

await s3.putObject(params, (error, data) => {
  if (error) {
    console.log(error);
  } else {
    console.log(data);
  }
});

also change the contentType & Encoding as:

let params = {
  Bucket: bucket,
  Key: filename,
  Body: rawdata,
  ContentEncoding: 'base64',
  ContentType: 'image/jpeg'
  ACL: 'public-read'
};

Upvotes: 1

Related Questions