Get file extension from uploaded file

svjn picture svjn · May 27, 2014 · Viewed 12.7k times · Source

Here my requirement is to upload the file and to store it in the disk. I have no problem in storing it in disk, but getting the extension of the file. The problem is when I click on upload and processing the file to store in disk, it is saved as a temp file with following name

"/tmp/multipartBody6238081076014199817asTemporaryFile"

here the file doesn't have an extension. So any of the following libraries doesn't help me get the extension of the file.

FileNameUtils.getExtension()

or

Files.getFileExtension(path)

I've even tried to get it through it's attributes, but it doesn't have an option to get the file extension.

Path path = Paths.get("/**/**/filepath");
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);

HTML code:

<input type="file" name="fileInput" class="filestyle"  data-classIcon="icon-plus" data-classButton="btn btn-primary" >

Get file object from Play framework:

MultipartFormData body = request().body().asMultipartFormData();
FilePart fileInput = body.getFile("fileInput");
File file = fileInput.getFile();

Any help to extract file extension is highly appreciated.

Thanks,

Answer

svjn picture svjn · May 27, 2014

I have found the solution for this. Actually this is of Play framework. I got the file using following code.

MultipartFormData body = request().body().asMultipartFormData();
FilePart fileInput = body.getFile("fileInput");
File file = fileInput.getFile();

I tried to get the name of file using this File object (which is used to store in a tmp location). But I missed to notice that FilePart object contains all file details that was uploaded. Then I figured it out.

fileInput.getFilename() gives me the uploaded file name with extension. It solves my problem.

Thanks for Cataclysm for helping me out. Surely the one he gave is the best answer for other framework like Struts/Spring or core servlets.