0
I have the code below where I upload a file and want to get its contents in a variable.
For this I use the function onload
that gets me the result
, which is the contents of the archive.
But the variable gives undefined
outside the onload
, how to make this result be used outside this function?
if(event.target.files.length > 0) {
let fileContent;
let file = event.target.files[0];
let fileReader = new FileReader();
fileReader.onload = function() {
fileContent = fileReader.result;
console.log(fileContent); //aqui eu tenho o conteúdo completo do arquivo
};
fileReader.readAsText(file);
console.log(fileContent); //aqui é undefined
}
}
No parameter is passed in
fileResult
.Have you tried to print the result of the file ? .– Victor Henrique
It will only exist inside the onload because it is the function that is called when it finishes receiving the file
– Eduardo Vargas
@Victorhenrique did not understand which fileResult would be
– Sabrina
@Eduardovargas yes, I need a way to make that information persist and appear outside that function.
– Sabrina
You can set the value to a property of your component. But it will only be with the value when function run because it is the same.
– Eduardo Vargas
You think you’ve got some time before the file’s uploaded.
– Eduardo Vargas
@Eduardovargas, right, could show me an example of how to return this result to what I’m looking for?
– Sabrina
The behavior of the code you shared is what is expected, since it is an asynchronous API. What do you want to do with the result later? It’ll be easier to help you if we understand the context.
– Leonardo Lima
@Leonardolima I want to save this value in a variable and then mount an object and save via api.
– Sabrina