Skip to content
Advertisement

Convert Data URI to File then append to FormData

I’ve been trying to re-implement an HTML5 image uploader like the one on the Mozilla Hacks site, but that works with WebKit browsers. Part of the task is to extract an image file from the canvas object and append it to a FormData object for upload.

The issue is that while canvas has the toDataURL function to return a representation of the image file, the FormData object only accepts File or Blob objects from the File API.

The Mozilla solution used the following Firefox-only function on canvas:

JavaScript

…which isn’t available on WebKit browsers. The best solution I could think of is to find some way to convert a Data URI into a File object, which I thought might be part of the File API, but I can’t for the life of me find something to do that.

Is it possible? If not, any alternatives?

Advertisement

Answer

After playing around with a few things, I managed to figure this out myself.

First of all, this will convert a dataURI to a Blob:

JavaScript

From there, appending the data to a form such that it will be uploaded as a file is easy:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement