Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Stripping path out of a filename

 
Jacob Fenwick
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've built a fileupload jsp using Apache Commons fileUpload and I want to get the original filename of an uploaded file.
I put the file into a FileItem object and use the getName function. When I'm in Firefox it works perfectly, as it gets just the name and not the path. However when I'm in IE it uses the entire path of the file as the name. I want it to work the way it does in Firefox, I want to get only the name and not the path. Has anyone encountered this problem, and if you did, how did you solve it?
This is not necessarily specific to the Apache Commons fileUpload, I imagine the problem of stripping a path out of a filename is something people encounter often.
 
Jacob Fenwick
Ranch Hand
Posts: 55
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Er... nevermind. It helps to read FAQs, heh.


Why does FileItem.getName() return the whole path, and not just the file name?
Internet Explorer provides the entire path to the uploaded file and not just the base file name. Since FileUpload provides exactly what was supplied by the client (browser), you may want to remove this path information in your application. You can do that using the following method from Commons IO (which you already have, since it is used by FileUpload).

String fileName = item.getName();
if (fileName != null) {
filename = FilenameUtils.getName(filename);
}


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic