Search code examples
javascripthtmlfileapipolyfills

read Data URL with File API polyfill


I am trying to use the File API library (https://github.com/mailru/FileAPI) as a fallback for browsers which do not support the File API, in order to read a file as a Data URL and pass that on to another function.

I have this code:

function handleFileSelect(event) {
    // If supported, use native File API.
    if(window.FileReader != null) {
        console.log('Using native File API.'); // !
        var files = event.target.files;
        for(var i = 0, f; f = files[i]; i++) {
            var reader = new FileReader();
            reader.onload = function(event) {
                insertImage(event.target.result);
            };
            reader.readAsDataURL(f);
         }
    }
// Otherwise, use fallback polyfill for browsers not supporting native API.
else {
    console.log('Using polyfill for File API.'); // !
    var file = FileAPI.getFiles(event.target);
    FileAPI.readAsDataURL(file, function(evt) {
        console.log(evt);
    });
  }
}

However, console.log(evt) returns an Object which reports error: "filreader_not_support_DataURL".

Have I done something wrong with File API polyfill or is there a shim or other polyfill I have to use to get data URLs to work?

Thanks.

-- Sam.


Solution

  • Feature is implemented yet via flash - thanks to the author of FileAPI plugin.

    // bind to your upload container
    var el = document.getElementById('uploadElementId');
    FileAPI.event.on(el, 'change', function (evt/**Event*/) {
        var files = FileAPI.getFiles(evt);
        // get Data URL for the first file
        FileAPI.readAsDataURL(files[0], function (dataUrlObject) {
            if (dataUrlObject.type == 'load') {
                // Success                    
                var dataUrl = dataUrlObject.result;
            }
        });
    });
    

    Whole thread here: https://github.com/mailru/FileAPI/issues/153