javascripthtmlfile

How to get file name when user selects a file via <input type="file" />?


I've seen similar questions before, which ends up with no solution, because of security reasons.

But today I see hostmonster has successfully implemented this when I opened a ticket and attached a file in their backend.

It works both with firefox and IE(version 8 to be exact).

I've verified it's exactly client side scripting; no request is sent(with firebug).


Solution

  • You can get the file name, but you cannot get the full client file-system path.

    Try to access to the value attribute of your file input on the change event.

    Most browsers will give you only the file name, but there are exceptions like IE8 which will give you a fake path like: "C:\fakepath\myfile.ext" and older versions (IE <= 6) which actually will give you the full client file-system path (due its lack of security).

    document.getElementById('fileInput').onchange = function () {
      alert('Selected file: ' + this.value);
    };