Explain Codes LogoExplain Codes Logo

Convert Data URI to File then append to FormData

javascript
blob-conversion
data-uri
form-data
Nikita BarsukovbyNikita BarsukovยทJan 10, 2025
โšกTLDR

To convert a Data URI to a File and append to FormData, here's the quick guide:

function dataURItoFormData(dataURI, filename) { // Decoding the base64 data like a pro ๐Ÿ˜‰ let byteString = atob(dataURI.split(',')[1]); // Extracting the MIME type, "ninja style" ๐Ÿ’ผ let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // Composing our Uint8Array, byte by byte ๐ŸŽถ let ia = new Uint8Array(byteString.length); for (let i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } // Constructing our file from the blob, piece by piece ๐Ÿ—๏ธ let file = new File([ia], filename, {type: mimeString}); // Adding file to FormData, like a boss ๐Ÿ˜Ž let formData = new FormData(); formData.append('file', file); return formData; } // Example usage var formData = dataURItoFormData('data:image/png;base64,iVBORw0K...', 'image.png');

Decoding the base64 segment, pulling out the MIME type, crafting a Blob, and finally, appending the File into FormData is basically what we're doing.

Code walk-through for data URI to file conversion

Let's deep dive into the code, line by line, to dissect the mechanism behind our data conversion operation.

Step 1: Break down the Data URI

First, we split the Data URI into the MIME type and base64 content.

let dataURI_parts = dataURI.split(','); let mimeString = dataURI_parts[0].split(':')[1].split(';')[0];

Next, we decode the base64 segment:

let byteString = atob(dataURI_parts[1]);

Step 2: Construct a Blob

We then create the binary data for the blob by converting the decoded string to a Uint8Array.

let ia = new Uint8Array(byteString.length); for (let i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); }

Subsequently, we construct the Blob with its corresponding MIME type:

let blob = new Blob([ia], {type: mimeString});

Stp 3: Prepare FormData for upload

Lastly, we create a FormData object and append the blob as a file for upload:

let formData = new FormData(); formData.append('file', blob, filename);

Modern browser "sleek" move

For modern browsers, canvas.toBlob() can cut short Blob creation. No manual conversion required:

canvas.toBlob(blob => { let formData = new FormData(); formData.append('file', blob, 'image.png'); });

"Unknown method"? Go manual! The Data URI conversion is your backup.

Fetch API: The alternative maestro

In case you want to go rogue, the fetch API offers a swanky way to convert base64 to a blob:

fetch(dataURI) .then(res => res.blob()) .then(blob => { let formData = new FormData(); formData.append('file', blob, 'image.png'); });

Ensuring cross-browser compatibility

Although we yearn for uber-modern implementations, we've got to think of our loyal oldie browsers:

  • The Blob constructor gets the green flag over the deprecated BlobBuilder.
  • ArrayBuffer has been booted out of the Blob team. Uint8Array is your main man.
  • Inject HTMLCanvasElement.prototype.toBlob and URL.createObjectURL() for stronger cross-browser compatibility.

Your coding checklist

Looking at various scenarios to keep your code Cruise-Control smooth.

WebKit browsers image handling

WebKit browsers like Safari love their own recipes. Our dataURItoFormData function gets along well, by creating a WebKit-friendly Blob.

Mobile applications preparedness

WebKit browsers dominate iOS. This approach fireproofs Data URIs uploads from canvas elements, a common scenario in mobile web apps.

Taming large files

For bulky Data URIs, performance matters. Leverage efficient JavaScript engines or web workers for smoother UI.

Debugging essentials

Investigate issues arising from malformed MIME types, corrupted base64 strings, or inconsistent browser Blob implementation by validating and gracefully handling errors.