2

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
});
1

1 Answer 1

2

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');   
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! Thank you very much.

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.