I haven\'t used JavaScript in a while and I can\'t seem to read a text file and display the contents.
I\'ve tried onload
as well as onloadend
I have the same the problem and I found a solution. You can't read the local file unless the user has permission. You can put a <input type="file">
on your page. When the file input change, you can read the data.
you can use ajax to get the content of your file:
var reader= new XMLHttpRequest();
reader.open('GET', '/pi.txt');
reader.onreadystatechange =readSuccess();
function readSuccess(evt) {
var field = document.getElementById('main');
field.innerHTML = reader.responseText;
};
reader.send();
Nothing worked for me. Below you can find my ugly solution, but it was the only one that did the job. In my case the user can upload up to 3 files, so the var iPDF can be 0,1,2.
var iPDF=UpdatedExistingNumberOfPDFfiles;
if (iPDF < NoMaxPDFfiles) {
var reader = new FileReader();
reader.readAsDataURL(files[iPDF-UpdatedExistingNumberOfPDFfiles]);
reader.onload = function (){
var PDFdataURL = reader.result;
var xhr = new XMLHttpRequest();
xhr.open("POST", "Observation_PDFUpload.php",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var NumberOfPDFfile = iPDF+1;
xhr.send("PDFfileURL="+PDFdataURL+"&PDFfileName="+PDFfileName+"-Annex-"+NumberOfPDFfile);
iPDF++;
if (iPDF < NoMaxPDFfiles) {
reader.readAsDataURL(files[iPDF-UpdatedExistingNumberOfPDFfiles]);
reader.onload = function (){
PDFdataURL = reader.result;
var xhr1 = new XMLHttpRequest();
xhr1.open("POST", "Observation_PDFUpload.php",true);
xhr1.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
NumberOfPDFfile = iPDF+1;
xhr1.send("PDFfileURL="+PDFdataURL+"&PDFfileName="+PDFfileName+"-Annex-"+NumberOfPDFfile);
iPDF++;
if (iPDF < NoMaxPDFfiles) {
reader.readAsDataURL(files[iPDF-UpdatedExistingNumberOfPDFfiles]);
reader.onload = function (){
PDFdataURL = reader.result;
var xhr2 = new XMLHttpRequest();
xhr2.open("POST", "Observation_PDFUpload.php",true);
xhr2.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
NumberOfPDFfile = iPDF+1;
xhr2.send("PDFfileURL="+PDFdataURL+"&PDFfileName="+PDFfileName+"-Annex-"+NumberOfPDFfile);
}
}
}
}
}
};
You can't grab a local file like that for security reasons.
Another underlying problem is that readAsText (and all the read functions) need the file's content and not its file path/name. You can grab this from the files collection of the input type="file" element. Here is how your code could work:
function readFile(file) {
var reader = new FileReader();
reader.onload = readSuccess;
function readSuccess(evt) {
var field = document.getElementById('main');
field.innerHTML = evt.target.result;
};
reader.readAsText(file);
}
document.getElementById('selectedFile').onchange = function(e) {
readFile(e.srcElement.files[0]);
};
Here is the jsfiddle: http://jsfiddle.net/fstreamz/ngXBV/1/
Note: this code not work in safari browser