Convert Blob to String in Anglican

Asked

Viewed 169 times

0

Hello, I have a code in Angularjs but it only works when I am in the browser debug.

    $scope.upload=function(){
        var newFiles = []; 
        $scope.carregando = true;
        angular.forEach($scope.files, function (item) {
            if(item.upload){
                item.idFicha = vm.ficha.id;
                var reader  = new FileReader();
                reader.readAsDataURL(item._file);

                //TODO Quero recuperar a substring do result.
                item.arquivo = reader.result.substr(reader.result.indexOf(',') + 1);

                newFiles.push(item);
                item.upload = false;
            }
        });
        service.uploadDocumento(newFiles);
        $scope.carregando = false;
    };

Well, when I take the breakpoint to execute the variable function item.file is null, but if I put the breakpoint and inspect the variable is with value and the function works perfectly.

What can be happening and what I must do to end this problem?

1 answer

0


It turns out that the API FileReader loads the data in a way asynchronous, this means that the code will continue to be processed, even if a certain function is not yet complete, that is, the code does not wait a certain line "finish your work".

When we have an asynchronous function, we also have some events available. In the case of FileReader, events are:

  • abort: You will be called when the procedure is aborted;
  • error: You’ll be called when there’s an error;
  • load: It will be called when the file is loaded;
  • loadstart: It will be called at the beginning of the file loading;
  • loadend: Will be called at the end of the file upload;
  • progress: It will be called while uploading the file.

In your case, you will have to add the whole rule of your code in the function load, for example:

const input = document.querySelector("input");

input.addEventListener("change", () => {
  for (let file of input.files) {

    let reader = new FileReader();
    reader.addEventListener("load", result => {
      console.log( `Teste #2: ${reader.result}` )
    })
    reader.readAsDataURL(file);
    console.log( `Teste #1: ${reader.result}` )
  }

});
<input type="file" multiple />

As I quoted, the FileReader does not wait for the file to be loaded in order to continue the remaining processing of the code, but when we add a breakpoint, we force this "pause". This is the time necessary for the FileReader can read the file and already store in the property result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.