Convert Blob to Non-angular String

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 perform the function the variable item.file is null, but if I put the breakpoint and inspect the variable is is with value and the function works perfectly.

What may be happening and what should I do to end this problem?

    
asked by anonymous 04.03.2018 / 05:50

1 answer

1

It turns out that the API FileReader loads the data in a

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

  • abort : Will be called when the procedure is aborted;
  • error : Will be called when there is an error;
  • load : Will be called when the file loads;
  • loadstart : Will be called at the beginning of loading the file;
  • loadend : Will be called at the end of loading the file;
  • progress : Will be called while loading the file.

In your case, you will have to add the entire rule of your code in the load function, 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've mentioned, FileReader does not expect the file to be loaded in order to continue the remaining processing of the code, but when we add a breakpoint , we force that "pause". This is the time it takes for FileReader to read the file and already store in the result property.

    
04.03.2018 / 08:22