views:

229

answers:

4

Hi, I am developing an application using JSF in Eclipse IDE with Derby as database. I have a feature to upload files to the database. But the file name is getting stored as "C:\Documents and Settings\Angeline\Desktop\test.txt" instead of "test.txt". How do I get to store only "test.txt" as file name in the database?

This is my code in JSF:

 File to Upload:

<t:inputFileUpload id="fileupload" value="#{employeeBean.upFile}" storage="file"/>

Java Bean Code:

 String fileName=upFile.getName();

The value of this fileName=C:\Documents and Settings\Angeline\Desktop\test.txt.

+2  A: 

new java.io.File(myPath).getName();

You could probably do something more efficient with only String operations but depending on the application load and other operations, it might not be worth it.

Xr
I'm not sure what happens if the client is a Linux and the server is a Windows. I mean: the path is one from the client's operating system, not the server.
helios
It won't work. Not with Sun's JRE, at least, since it uses `FileSystem.getSeparator()`.
Xr
+2  A: 
lastSlashIndex = name.lastIndexOf("\\");
if (lastSlashIndex == -1) {
    lastSlashIndex = name.lastIndexOf("/"); //unix client
}
String shortName = name;
if (lastSlashIndex != -1) {
    shortName = name.substring(lastSlashIndex);
}

Note that if the filename on *nix contain a \ this won't work.

Bozho
I'll check the lastSlashIndex before the substring call
helios
What if you are on *NIX and the file name has a backslash in it?
Xr
I don't think *NIX users run MSIE.
BalusC
A: 

I think it would be safer to see this not as a string manipulation problem, but as a path name parsing problem:

String filename = new File(pathname).getName()
Michael Borgwardt
+2  A: 

Tomahawk t:inputFileUpload is built on top of Apache Commons FileUpload and Apache Commons IO. In the FileUpload FAQ you can find an entry titled "Why does FileItem.getName() return the whole path, and not just the file name? " which contains the following answer:

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

In short, just use FilenameUtils#getName() to get rid of the complete path which has been unnecessarily appended by MSIE (all the other real/normal webbrowsers doesn't add the complete client side path, but just provide the sole filename as per the HTML forms specs).

So, all you basically need to do is replacing

String fileName = upFile.getName();

by

String fileName = FilenameUtils.getName(upFile.getName());
BalusC