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

隐身守侯 提交于 2019-12-08 08:59:25

问题


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.

  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.


来源:https://stackoverflow.com/questions/8553750/validation-how-to-check-if-the-file-being-uploaded-is-in-excel-format-apach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!