Categories
JavaScript Answers

How to convert Data URI to File then append to FormData with JavaScript?

Spread the love

To convert Data URI to File 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 url.

Then we call blob to convert the response to a blob.

Next, we create a FormData object.

And then we append the blob as an entry in the FormData object with append.

append takes the key, the value, and the file name as arguments.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *