Empty File Inputs in IE9

In all web development, you run into a bug that’s specific to a browser/version, and defies common sense. At least common sense in the way web development can make sense sometimes.

The past day or two, I have been debugging an issue that had me ready to pull my hair out. It’s specific to IE9 (or the new IE6), and file inputs not being sent to the server through a form POST.

The Trickery

To give some background, I had put together a little component in this web app to handle file upload. It was more of a hack than anything.

I positioned a button next to the file input, hid the file input, and attached some JavaScript to mimic a user clicking the file input via the button. After the user selects a file, I parsed the file name and displayed it in a label next to the button. All in all, I thought it was an elegant solution.

Simple example:

JS Bin on jsbin.com

The Problem

This solution works excellently….mostly. IE9 decides to rear its ugly head and decide the file inputs are empty upon submission of the form. Although the change event still fires, and  this.value actually has the path of the file in it.

Interesting to say the least.

Using the Chrome dev tools, I can see the input doesn’t have a value, even though the JS says it should. Seeing that it is IE9, I was ready to just say, “don’t use IE9”, but in my workplace, that’s not an option.

So…more work to be done.

The Key is in the Click

Upon reaching the point of almost resorting to head/desk exercises, I decided to just rip out the fanciness and revert back to traditional file inputs. Those worked beautifully. There goes my, “it wasn’t my code” excuse.

After doing some research and testing, it came down to the click on a file input. In JavaScript, clicking the button, would then call  click() on the file input. IE9 doesn’t treat all clicks equal. Once a file is selected, JavaScript knows about it, but the value isn’t set on the input. Hence, empty values posted to the server.

I did not try making the file input visible to see if that made somewhat of a difference, but that would break my design and I just can’t have that. 😛

Don’t Do This

Moral of the story, don’t use JavaScript to do a click on a file input. It won’t set the value of the input and you won’t see a file arrive on the backend. If you’ve worked with IE in any development capacity, I’m sure this is not the only weird behavior that’s cropped up.