7

Friends, Countrymen, Lend me your ears...

I'm signing my url for amazon s3, and then using fileReader and Fetch to put my file in s3. Though when I do I get a fun white square instead of my image: https://s3.amazonaws.com/hubbble/Gabe/lX4H0.png

const reader = new FileReader();
reader.onload = ((e) => {

  let s3headers = new Headers();
  s3headers.append("content-type", 'image/png');

  fetch(signedRequest, {
      method: 'PUT',
      headers: s3headers,
      body: e.currentTarget.result
  }).then((response)=>{
    console.log(response);
  });
});
  • Permissions Issue? Don't really think so as you can definitely view the image
  • Corrupted somehow?
  • Maybe an incorrect content type?

Thoughts? Thanks for any guidance, been banging my head against the wall on this!

Justin
  • 2,940
  • 3
  • 25
  • 43
  • you should change the accepted answer which spells out explicitly what needs to happen a little more clearly :) – Pinwheeler Apr 20 '21 at 02:49

2 Answers2

5

The contents of that appear to be a base64 encoded image. That is, you're uploading a text file and not a binary image (and then saying it is, a image/png) You could just convert it first doing something like this first.

Community
  • 1
  • 1
Jack
  • 20,735
  • 11
  • 48
  • 48
  • 2
    You're a gentlemen and a scholar. I knew it had to be something like that. Ended up using fetch to read the file, as suggested in one of the answers. Super simple and worked great! – Justin Dec 23 '16 at 19:01
5

If anyone is coming from a Node environment, the solution is to use the following code. I tested this and it works. There is no need for atob or doing some bytearray acrobatics.

      // base64DataString is the base64 string, which I assume you have
      // base64Data is a Buffer that is encoded in base64!
      // STEP 1: we remove the header of the dataUri string
      const base64Data = new Buffer.from(b64DataString.replace(/^data:image\/\w+;base64,/, ""), 'base64');


      // STEP 2: CALL PUT OBJECT
      s3.putObject(
        {
          Bucket: "your bucket name",
          Key: `yourfile.jpg`, // the key for S3 location 
          Body: base64Data,
          ContentEncoding: 'base64', // important to tell that the incoming buffer is base64
          ContentType: "image/jpeg", // e.g. "image/jpeg" or "image/png"
          ACL:'public-read'
        },
        (err, data) => {
          if(err) {
            reject(err)
            return;
          }
          console.log("UPLOAD SUCCESSFULLY:") //optional
          console.log(data) //optional
          resolve(data); // if this is in a promise, then include
        }
      )
KJ Ang
  • 305
  • 3
  • 9