Keir
Keir

Reputation: 607

FileReader read file undefined result

I wish to read the contents of an upload file into a Javascript variable.

The program used to work using file.getAsBinary but this is now deprecated and needs to be updated to use FileReader()

A form has a file upload selection an onsubmit runs a function uploadDB() in a javascript.

The variable dbname is passed okay as is the file name from the upload selection I can see it with an alert or console.log.

The final bfile variable to receive the file text is undefined. I have tried both readAsText and ReadAsBinary but bfile is undefined. The var declaration is in function uploadDB() and should be global to the inner function. If scope is somehow a problem how do I get the result in the bfile variable.

Its probably simple but I cannot get it to work. Can someone suggest something please. The html section is;

<form onsubmit="uploadDB()"; method="post">
Database <input type=text name="dbName" id="dbName" size=20>
<input type=file id="metaDescFile" size=50 >
<input type=submit value="Submit">
</form>

The js script is similar to (extraneous stuff edited out);

<script language="javascript" type="text/javascript">
<!--
    var uploadDB = function() {
        var input = document.getElementById('metaDescFile');
        var fname = document.getElementById('metaDescFile').value;
        var file=input.files[0];
        var bfile;

        reader = new FileReader();

        reader.onload = function(e) {  bfile = e.target.result }
        reader.readAsText(file);
        alert(bfile);   // this shows bfile as undefined


        // other stuff
    }

Upvotes: 7

Views: 17121

Answers (2)

Etienne Salimbeni
Etienne Salimbeni

Reputation: 582

Here is one answer to get the actual final byte array , just using FileReader and ArrayBuffer :

 const test_function = async () => {

      ... ... ...

      const get_file_array = (file) => {
          return new Promise((acc, err) => {
              const reader = new FileReader();
              reader.onload = (event) => { acc(event.target.result) };
              reader.onerror = (err)  => { err(err) };
              reader.readAsArrayBuffer(file);
          });
       }
       const temp = await get_file_array(files[0])
       console.log('here we finally ve the file as a ArrayBuffer : ',temp);
       const fileb = new Uint8Array(fileb)

       ... ... ...

  }

where file is directly the File object u want to read , notice that this is an async function...

Upvotes: 2

eikes
eikes

Reputation: 5061

as bfile gets set in the onload callback you won't be able to access outside that callback because the code is evaluated before the callback is fired.

Try this:

reader = new FileReader();
reader.onload = function(e) {  
  bfile = e.target.result 
  alert(bfile);   // this shows bfile
}
reader.readAsText(file);

Upvotes: 6

Related Questions