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.

function getFilename(input_file_id) {
  file = document.getElementById(input_file_id).value;
  if (file.indexOf('/') > -1) file = file.substring(file.lastIndexOf('/') + 1);
  else if (file.indexOf('\\') > -1) file = file.substring(file.lastIndexOf('\\') + 1);
  return file;
}

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.

No TweetBacks yet. (Be the first to Tweet this post)

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.


(No Ratings Yet)
 Loading ...

tags: , ,

One Response to “Javascript Get Filename Of HTML Form Input File”

  1. 1
    debrian Says:

    nice info friends..

    http://www.hetpaard.info

Leave a Reply