Validation : how to check if the file being uploaded is in excel format? - Apache POI

Is there any way I can check if the file being uploaded is in excel format? I am using Apache POI library to read excel, and checking the uploaded file extension while reading the file.

Code snippet for getting the extension

String suffix = FilenameUtils.getExtension(uploadedFile.getName());

courtesy BalusC : uploading-files-with-jsf

String fileExtension = FilenameUtils.getExtension(uploadedFile.getName());
if ("xls".equals(fileExtension)) {
//rest of the code

I am sure, this is not the proper way of validation.

Sample code for browse button

<h:inputFileUpload id="file" value="#{sampleInterface.uploadedFile}" 
        valueChangeListener="#{sampleInterface.uploadedFile}" />

Sample code for upload button

<h:commandButton action="#{sampleInterface.sampleMethod}" id="upload" 

User could change an extension of a doc or a movie file to "xls" and upload,then it would certainly throw an exception while reading the file.

Just hoping somebody could throw some input my way.


You can't check that before feeding it to POI. Just catch the exception which POI can throw during parsing. If it throws an exception then you can just show a FacesMessage to the enduser that the uploaded file is not in the supported excel format.

Please try to be more helpful to the poster. Of course you can test before poi. Regular tests, to be performed before the try/catch, include the following. I suggest a fail-fast approach.

  1. Is it a "good" file?

    1. if file.isDirectory() -> die and exit.
    2. if !file.isReadable() -> die and exit.
    3. if file.available <= 100 -> die and exit (includes file size zero)
    4. if file.size >= some ridiculous large number (check your biggest excel file and multiply by 10)
  2. File seems good, but is contents like Excel?

    1. Does it start with "ÐÏà" -> if not, die.
    2. Does it contain the text "Sheet"-> if not, die
    3. Some other internal excel bytes that I expected from you guys here.

Need Your Help

PHP generated XML parsing failed

php xml codeigniter domdocument

In my CodeIgniter 2.x project with PHP 5.3.x I use following function to render Dom Document as XML response. Every things are goes fine. But generated XML parsing failed due to some malformed unex...

Auto-adjust thumbnail's position in a DIV (based on browser window width)?

php javascript html css

I have a website that is displaying thumbnails that fits to the side. I have a bunch of thumbnails I want to fit. How it is now, there is a big gap when a picture goes to the next line.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.