3

我为本地文件处理创建了一个测试,但无法让“文件”类型返回 Chrome 或 Firefox 中的任何内容。Chrome 没有给出错误,并且表现得好像从未调用过 FileReader(),而 Firefox 给出了一个奇怪的错误。FileReader() 适用于 Blob 类型。有任何想法吗?请参阅下面的测试代码:

<head>

<script language="JavaScript" type="text/javascript">

var ContentString='(empty)';

var reader = new FileReader();
var testBLOB = new Blob(['Test Blob'], { "type" : "text/plain" });
reader.onload = function(event) {ContentString = event.target.result;};
reader.onerror = function(event) {alert('Load error!');};

function WriteContents(Iteration,FileOrBlob) 
{
    if (Iteration==0) 
    {
        if (FileOrBlob==0) 
        {
            try 
            {
            var fileUpload=document.getElementById("inputFile");
            //alert(fileUpload.type);
            reader.readAsText(fileUpload/*, "UTF-8"*/);
            }
            catch(err) {alert(err.message);}
        }
            else
        {
        reader.readAsText(testBLOB/*, "UTF-8"*/);
        }
    }

    document.getElementById("Iteration").innerHTML=Iteration;
    document.getElementById("ContentString").innerHTML=ContentString;
    document.getElementById("error").innerHTML=reader.error;
    document.getElementById("readyState").innerHTML=reader.readyState;
    document.getElementById("result").innerHTML=reader.result;

    setTimeout('WriteContents('+(Iteration+1)+','+FileOrBlob+');',5000);
}

if (window.File && window.FileReader && window.FileList && window.Blob)  {document.write('OK<br>');} else {document.write('Browser Error<br>');}

</script>

</head>

<br>
<input type="file" id="inputFile" name="inputFile" onchange="WriteContents(0,0);">&nbsp;
<input type="button" onclick="WriteContents(0,1);" value="Use Test Blob">
<br><br>
<table border=1>
<tr><td>Iteration</td><td id="Iteration">Choose File or Blob Above (one time only please!)</td></tr>
<tr><td>ContentString</td><td id="ContentString"></td></tr>
<tr><td>error</td><td id="error"></td></tr>
<tr><td>readyState</td><td id="readyState"></td></tr>
<tr><td>result</td><td id="result"></td></tr>
4

1 回答 1

3

在这篇文章中找到了答案:

文件 API:返回文件引用(对象)或整个文件内容(字符串)?

您需要访问“文件”的 blob 部分 - 这些行

var fileUpload=document.getElementById("inputFile");
reader.readAsText(fileUpload/*, "UTF-8"*/);

应该

var fileUpload=document.getElementById("inputFile").files[0];
reader.readAsText(fileUpload/*, "UTF-8"*/);

只有9个字符!!

于 2013-01-17T16:07:00.560 回答