Reputation: 71
I created a test for local file handling, but can't get the 'file' type to return any contents in Chrome or Firefox. Chrome gives no error and acts like there was never a call to the FileReader(), and Firefox gives a strange error. FileReader() works fine on the Blob type. Any ideas? See test code below:
<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);">
<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>
Upvotes: 3
Views: 12213
Reputation: 71
Found the answer in this post:
File API: Returns file reference (object) or whole file content (string)?
You need to access the blob part of the 'file' - these lines
var fileUpload=document.getElementById("inputFile");
reader.readAsText(fileUpload/*, "UTF-8"*/);
should be
var fileUpload=document.getElementById("inputFile").files[0];
reader.readAsText(fileUpload/*, "UTF-8"*/);
Only 9 characters out!!
Upvotes: 3