S Jagdeesh
S Jagdeesh

Reputation: 1553

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" 
value="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.

Upvotes: 1

Views: 3941

Answers (2)

Kos Petoussis
Kos Petoussis

Reputation: 41

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.

Upvotes: 0

BalusC
BalusC

Reputation: 1108782

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.

Upvotes: 4

Related Questions