Nguyễn Duy Phú
Nguyễn Duy Phú

Reputation: 31

FileItem.getName() return all path of file not only file name in Java

I have some problem while get file Name. It always return all path of my file not only file name

List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
            FileItem fileItem = fileItemsIterator.next();
            System.out.println("FileName="+fileItem.getName());

Output is FileName=C:\Users\Administrator\Downloads\demoUpload2.war but I need only demoUpload2.war.

Upvotes: 1

Views: 4891

Answers (1)

Rahman
Rahman

Reputation: 3785

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); }

Ref :http://commons.apache.org/proper/commons-fileupload/faq.html#whole-path-from-IE You can do this :

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

Upvotes: 3

Related Questions