I'm trying to make a file uploader for my blog system which would just let users drop files in it and it would automatically upload them to server. Strangely (for me), console.log outputs dataArray before it gets filled, while calling it after a timeout outputs it correctly.
For example, if I drop 4 files on my drop area, I would get this:
[]
[file1, file2, file3, file4]
Then I drop 4 more files without uploading/refreshing and I get:
[file1, file2, file3, file4]
[file1, file2, file3, file4, file5, file6, file7, file8]
So my script is working asynchronously for some reason? Can somebody tell me what I'm doing wrong here?
var dataArray = [];
$('.dropArea').bind(
{
drop: function(e)
{
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
$.each(files, function(index, file)
{
var fileReader = new FileReader();
fileReader.onload = (function(file)
{
return function(e)
{
var image = this.result;
dataArray.push({
name : file.name,
value: image
});
}
})(files[index]);
fileReader.readAsDataURL(file);
});
console.log(dataArray);
setTimeout(function() { console.log(dataArray) }, 1000);
},
});
