Javascript Get Filename Of HTML Form Input File

When I wanted to get the filename of the file I just uploaded from the HTML form using Javascript, I found out that Internet Explorer and Firefox both output differently (yeah, this is the consequence for always sticking to Firefox). IE outputs the absolute path of the file (this means, it includes the root folder and its subdirectories) while Firefox outputs only the filename. I was expecting even Google Chrome to behave like Firefox but it turned out it gave the same result as IE. If you wish to know if Mac’s Safari browser does output the same as IE and Chrome, then the answer is yes (notice Safari and Chrome’s HTML form file input design is the same? This was done on purpose to avoid a common security flaw). To get around this problem, you would have to check the input file field if there are any \ or / characters in it, and if so, using the lastIndexOf() method to return the position of the occurence of the searched string, use it together with the substring() function. See the function below.

The parameter I used for the function is the id name of the element since I prefer getting elements by id rather than using their form’s names.

Related Posts Plugin for WordPress, Blogger...

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *