I'm trying to do a simple file upload in my HTML and Javascript.
The way that I've set it up is by having an <input type="file" id="file-upload-input"/> with a loadFile function subscribed to its onChange event. (I have this input invisible just because it looks bad.)
I then have a <button/> with the function handleBrowseClick subscribed to its onclick event.
Both of the above controls seem to work fine: when I click on my <button/>, handleBrowseClick is called, which clicks my <input type="file">, causing the file dialog to open. However, an issue occurs once I select a file and press "open" in the dialog (which triggers the <input type="file">'s onChange event, thus calling my loadFile function).
As you can see in the Javascript, at this point to try to read the file by getting my <input type="file">, accessing its files property, and trying to get the first element of that array so that I can read from it with the FileReader (which works fine).
However, no matter what file I select, the files array is always empty (and thus my alert prints out "# Files Selected: 0")! After extensive debugging and narrowing the problem, I discovered that in handleBrowseClick(), if I remove my debugging code that slightly modifies the body of the HTML, then the file upload suddenly works perfectly! (The alert prints out "# Files Selected: 1".)
So here's my question: why would a line that
- only modifies the body of the HTML (but doesn't affect any of the controls)
- is irrelevant to the file upload functions
prevent my file upload from working?
function handleBrowseClick()
{
document.getElementById("upload-file-input").click();
// if I comment out this line, then the file upload works
document.body.innerHTML += "<br/>Browsing...";
}
function loadFile()
{
var elem = document.getElementById("upload-file-input");
var files = elem.files;
alert("# Files Selected: " + files.length);
var file = files[0];
if (!file) return;
var reader = new FileReader();
reader.onload = function()
{
// do stuff with reader.result
// example:
document.getElementById("file-content").innerHTML = reader.result;
};
reader.readAsText(file);
}
<!DOCTYPE html>
<html>
<head>
<script src="course_chart.js"></script>
</head>
<body>
<input type="file" accept=".txt" id="upload-file-input" style="display: none" onChange="javascript:loadFile()"/>
<button onclick="javascript:handleBrowseClick()" id="choose-file-button">Load File</button>
<div id="file-content"></div>
</body>
</html>