验证:如何检查上传的文件是否为 excel 格式?- 阿帕奇兴趣点 [英] Validation : how to check if the file being uploaded is in excel format? - Apache POI

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

问题描述

有什么办法可以检查上传的文件是否为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.

获取扩展的代码片段

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

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.

浏览按钮的示例代码

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

上传按钮的示例代码

<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 格式?- 阿帕奇兴趣点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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