验证:如何检查是否被上传的文件是在Excel格式? - Apache的POI [英] Validation : how to check if the file being uploaded is in excel format? - Apache POI

查看:502
本文介绍了验证:如何检查是否被上传的文件是在Excel格式? - Apache的POI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法,我可以检查是否被上传的文件是在Excel格式?我使用Apache POI库来读取Excel和读取文件时检查上传的文件扩展名。

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段为获得延长

Code snippet for getting the extension

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

BalusC:上传 - 文件 - 使用的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.

样品code的浏览按钮

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

样品code上传按钮

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

用户可以变更文件或电影文件的扩展名XLS,并上传,然后将它肯定会在读取文件抛出异常。

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.

推荐答案

您无法确认其送入POI之前。正好赶上这POI可以解析过程中抛出异常。如果它抛出一个异常,那么你可以只显示一个的FacesMessage 到上传的文件是不是在支持Excel格式终端用户。

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.

这篇关于验证:如何检查是否被上传的文件是在Excel格式? - Apache的POI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆