Convert Data URI to File then append to FormData
To convert a Data URI to a File and append to FormData, here's the quick guide:
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.
Next, we decode the base64 segment:
Step 2: Construct a Blob
We then create the binary data for the blob by converting the decoded string to a Uint8Array.
Subsequently, we construct the Blob with its corresponding MIME type:
Stp 3: Prepare FormData for upload
Lastly, we create a FormData object and append the blob as a file for upload:
Modern browser "sleek" move
For modern browsers, canvas.toBlob()
can cut short Blob creation. No manual conversion required:
"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:
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 deprecatedBlobBuilder
. ArrayBuffer
has been booted out of theBlob
team.Uint8Array
is your main man.- Inject
HTMLCanvasElement.prototype.toBlob
andURL.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.
Was this article helpful?