0

Here is a task I thought might be easy, but I really don't get it. There is a dropzone on an empty page. The user can drop files and the information of the file is then going to be stored in a database.

But the function that passes the information, only passes the last file dropped. But if I log the base64URL in the filereader.onload event all URLs are logged to the console.

dropzone.addEventListener('drop', function(e) {
    e.preventDefault();
    e.stopPropagation();
    dropzone.classList.remove('highlight');

    files = e.dataTransfer.files; 
   
    if(!files) return;
  

    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var getFileName = file.name;
        var getFileSize = file.size;
        var getFileModifiedDate = file.lastModifiedDate;
        var base64single;
        console.log(i + " " + getFileName + " " + getFileSize + " " + getFileModifiedDate);

     
        var fileReader = new FileReader();
        fileReader.onload = function (e) {
            base64single = e.target.result;
            console.log(base64single);
            Microsoft.Dynamics.NAV.InvokeExtensibilityMethod('sendFileData', [base64single, getFileName, getFileSize, getFileModifiedDate]); //This function passes to a database
        };
        fileReader.readAsDataURL(file);

        }
    }, false);

How do I have to change this to make it work? I would try with promises but I dont understand how they work yet.

  • Because you're using `var`, all of your variables have function scope. So each iteration of the loop writes over the previous iteration's values. The functions you're creating in the loop (the `onload` handlers) each close over the **same** variables, which are updated every time. One simple way to fix it is to make the code in the loop body its own function and call that function from the loop. That way, the variables are local to that function call, and each handler has a reference to its own set of variables. In modern environments, you can also use `let` or `const` for the ... – T.J. Crowder Sep 21 '20 at 07:05
  • ...variables in the loop body, and then each loop iteration will get its own variables. Your loop body is long enough that I'd probably make it its own function, though. In both cases, see the [linked question](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example)'s answers for details. – T.J. Crowder Sep 21 '20 at 07:05

0 Answers0