Mark
Mark

Reputation: 2587

HTML FileReader

function fileSelected() {
    // get selected file element
    var files = document.getElementById('files[]').files;

    for (var i = 0; i < files.length; i++)  //for multiple files          
    {
        (function (file) {
            var fileObj = {
                Size: bytesToSize(file.size),
                Type: file.type,
                Name: file.name,
                Data: null
            };

            var reader = new window.FileReader();
            reader.onload = function (e) {
                fileObj.Data = e.target.result;
            };
            // read selected file as DataURL
            reader.readAsDataURL(file);

           //Create Item
           CreateFileUploadItem(fileObj);

        })(files[i]);
   }
}

function CreateFileUploadItem (item) {
    console.log(item);

    $('<li>', {
        "class": item.Type,
        "data-file": item.Data,
        "html": item.Name + ' ' + item.Size
    }).appendTo($('#filesForUpload'));
}

So when console.log(item) gets run in the CreateFileUploadItem function it shows the item.Data. YET it won't add it to the data-file of the LI. Why is that?

Upvotes: 0

Views: 718

Answers (1)

Creakazoid
Creakazoid

Reputation: 331

The call to readAsDataURL is asynchronous. Thus, the function call is likely returning prior to the onload function being called. So, the value of fileObj.Data is still null when you are attempting to use it in CreateFileUploadItem.

To fix it, you should move the call to CreateFileUploadItem into your onload function. As for the console logging the proper value, you can't rely on that being synchronous either. I think using a breakpoint during debugging at that line instead will likely show the true null value.

Upvotes: 2

Related Questions