Reputation: 1553
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
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.
Is it a "good" file?
File seems good, but is contents like Excel?
Upvotes: 0
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