1

I have a piece of HTML which I converted into an image using html-to-image and now I need to upload that image file to s3.

What I get after conversion is base 64 url. I have my s3 setup on remote backend where I send files to the api route and it uploads it to s3 and returns the s3 url for the file.

How can I convert this base url to image obj and send it to the api?

Function to convert html to img:

htmlToImage.toPng(document.getElementById('my-node'))
  .then(function (dataUrl) {
    // do stuff with url
});
tmhao2005
  • 14,776
  • 2
  • 37
  • 44
Surya Mahla
  • 483
  • 5
  • 20

1 Answers1

1

There is a pretty simple common function which converts image data url to a file object defined as following:

function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while(n--){
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type:mime });
}

// Usage in your case

htmlToImage.toPng(document.getElementById('my-node'))
  .then(function (dataUrl) {
    const yourFile = dataURLtoFile(dataUrl, 'yourImageName');   
  });
tmhao2005
  • 14,776
  • 2
  • 37
  • 44