I'm trying to send multiple files to dropbox using JavaScript and Ruby/Rails. First I have to decode an image with qr code and send it to my server in Ruby, then send it to dropbox. The problem is, when I'm trying to decode a file and send it, it is not going in the right order. I'm aware that this is probably because of the onload function of the reader. But how can I solve this and why this is the way it is? PS: My qr code have to be a number (a code from the db), that's why I'm using 'isnum' ps2: I tried 10 files and in my console.log that has 'j' have printed in this orded: 1, 7, 7, 4, 6, 6, 6, 6, 3, and 0. How can I make it to not repeat these indexes?
function setupReader(file, j){
var reader = new FileReader();
reader.onload = function (e) {
qrcode.decode(e.target.result);
qrcode.callback = function(a){
console.log("callback", j);
var isnum = /^\d+$/.test(a);
var form_data = new FormData();
count_send++;
if (isnum){
form_data.append("code", a);
form_data.append("file", file);
// console.log(form_data);
var request = new XMLHttpRequest();
request.open('POST', '/docs/baixaponto', /* async = */ false);
request.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
request.send(form_data);
if (returnedStatus != 200){
error_files_dropbox_baixa_filesimgs.push(e.target.result);
e.target.result = "";
error_files_dropbox_baixa_arquivos.push( returnedStringFinal );
error_files_dropbox_baixa.push( file );
error_files_dropbox_baixacount++;
}
else{
success_files_filesimgs.push(e.target.result);
e.target.result = "";
success_files_arquivos.push( returnedStringFinal );
success_files.push( file );
success_filescount++;
}
}
else {
error_files_decode_filesimgs.push(imgcoded64);
e.target.result = "";
error_files_decode.push( file );
error_files_decodecount++;
}
if ( count_send == count ){
//function that opens a modal with file results
setTimeout(showdetalhedfiles, 2000);
}
};
}
reader.readAsDataURL(file);
}
The other function is:
function readqrcode(){
f = document.getElementById('myfiles');
count = f.files.length;
if (f.files && f.files[0]) {
for (var i = 0; i < count; i++) {
setupReader(f.files[i], i);
}
}
else{
alert("Nenhum arquivo selecionado");
}
}