How is it possible to pass the name and size of a file to the .onload event of JavaScript's FileHandler. As you can see I'm using the (still undeclared) variables size
and name
in my Ajax call below. However, I somehow have to pass them from the getData()
function.
I've found Pass a parameter to FileReader onload event but it doesn't seem to work for me.
getData('file2093',
function(e) {
new Ajax.Request('/documents/2093', {
asynchronous:true, evalScripts:true, method:'patch', parameters:'document_payload=' + btoa(e.target.result) + '&document_filename=' + btoa(name) + '&document_size=' + btoa(size)
});
})
function getData(inputField, onLoadCallback){
var input = document.getElementById(inputField);
var file = input.files[0];
var size = file.size;
var name = file.name;
var fr = new FileReader();
fr.onload = onLoadCallback
fr.readAsDataURL(file);
}
Use bind, arguments after the first one get passed to the called function, along with any other arguments passed during the function invocation.
getData('',function(size,name,e){
...
});
...
fr.onload = onLoadCallback.bind(fr,size,name);
Otherwise set the onload to an anonymous function that calls the callback
fr.onload = function(e){
onLoadCallback(size,name,e);
};
pass the filereader object as well in the second snippet if you need access to the reader object, the first snippet sets the context of the callback function so you can access the reader object by this
in the callback