How to convert data URI to File and then append to FormData with JavaScript?

Spread the love

Sometimes, we want to convert data URI to File and then append to FormData with JavaScript.

In this article, we’ll look at how to convert data URI to File and then append to FormData with JavaScript.

How to convert data URI to File and then append to FormData with JavaScript?

To convert data URI to File and then append to FormData with JavaScript, we use fetch.

For instance, we write

const url =
  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

const res = await fetch(url);
const blob = await res.blob();
const fd = new FormData();
fd.append("image", blob, "filename");

console.log(blob);

to call fetch with the base64 url.

Then we call res.blob to get the blob object from the promise.

Next, we call fd.append to attach the blob with key 'image' and file name 'filename'.

Conclusion

To convert data URI to File and then append to FormData with JavaScript, we use fetch.

Leave a Reply

Your email address will not be published.