Convert Blob to File List in javascript

madan V picture madan V · May 29, 2014 · Viewed 8.4k times · Source

I am using the following code to covert a canvas image to blob.
In order to convert the blob to a file/filelist object, I need to pass that filelist to file handler.

Mycode:

var canvas1 = document.getElementById("preview");
var theImage = document.getElementById("blahProfile");
theImage.src = canvas1.toDataURL();
var blob = dataURItoBlob(theImage.src);

Is there any way to convert that blob to a file object?

Answer

apsillers picture apsillers · May 29, 2014

File objects contain more information than Blob objects, with properties like lastModifiedDate, and fileName. It doesn't make sense for your image data to have either of those properties, because it's not a file.

I assume you FileList handler users a FileReader to read File objects. However, the FileReader methods can process Blob objects as well (because File is a subclass of Blob). Thus, you can either:

  • extract your FileReader code into a separate function that accepts a Blob or File (and possibly a resolution callback function) amd call that function when handling each of your FileList items and when processing your Blob of image data

  • if your FileList handler only accesses list items by index (e.g., myFileList[i]) then you could fake a FileList simply by using an array of Blobs. For example, this function works with either a real FileList or array of Blobs:

    function processFileList(list) {
        var reader = new FileReader();
        reader.readAsText(list[0]);
        reader.addEventListener("loadend", function() {
            console.log(reader.result);
        });
    }