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
    }

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);

I realise this question is old, but you can access bfile variable using a callback. Code would look like:

var callback = function(fileData) {
  alert(fileData); // Or do something else with it...
}

var reader = new FileReader();
reader.onload = function(e, callback) {
  callback(e.target.result);
}

reader.readDataAsURL(file);
链接地址: http://www.djcxy.com/p/94614.html

上一篇: ios上传文件到亚马逊S3

下一篇: FileReader读取未定义的文件结果