问题
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.
回答1:
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.
回答2:
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?
- if file.isDirectory() -> die and exit.
- if !file.isReadable() -> die and exit.
- if file.available <= 100 -> die and exit (includes file size zero)
- if file.size >= some ridiculous large number (check your biggest excel file and multiply by 10)
File seems good, but is contents like Excel?
- Does it start with "ÐÏà" -> if not, die.
- Does it contain the text "Sheet"-> if not, die
- Some other internal excel bytes that I expected from you guys here.
来源:https://stackoverflow.com/questions/8553750/validation-how-to-check-if-the-file-being-uploaded-is-in-excel-format-apach