javascript FileReader 读取文件未定义结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14225190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:03:36  来源:igfitidea点击:

FileReader read file undefined result

javascriptfilereader

提问by Keir

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

我希望将上传文件的内容读入 Javascript 变量。

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

该程序曾经使用 file.getAsBinary 工作,但现在已弃用,需要更新以使用 FileReader()

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

表单有一个文件上传选择,onsubmit 在 javascript 中运行一个函数 uploadDB()。

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.

变量 dbname 和上传选择中的文件名一样可以正常传递,我可以通过警报或 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.

接收文件文本的最终 bfile 变量未定义。我已经尝试了 readAsText 和 ReadAsBinary 但 bfile 未定义。var 声明在函数 uploadDB() 中并且应该是内部函数的全局变量。如果范围在某种程度上是一个问题,我如何在 bfile 变量中获得结果。

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

它可能很简单,但我无法让它工作。有人可以建议一些东西吗。html 部分是;

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

js 脚本类似于(编辑掉无关的东西);

<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
    }

回答by eikes

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

由于 bfile 在onload回调中设置,您将无法在该回调之外访问,因为在触发回调之前评估代码。

Try this:

试试这个:

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