Java 上载excel文件时,内容类型不符合预期
我有以下代码:Java 上载excel文件时,内容类型不符合预期,java,jsf,tomahawk,Java,Jsf,Tomahawk,我有以下代码: <h:form id="form" enctype="multipart/form-data"> <t:inputFileUpload id="eFile" value="#{Parser.uploadFile}" storage="file"/> <t:commandButton value="Parse" action="#{Parser.parse}"/> </h:form> 在我的project
<h:form id="form" enctype="multipart/form-data">
<t:inputFileUpload id="eFile" value="#{Parser.uploadFile}" storage="file"/>
<t:commandButton value="Parse" action="#{Parser.parse}"/>
</h:form>
在我的project everywhere中,excel文件根据其内容类型进行检查,它们在不久前工作正常,但现在我不明白它们为什么不能正常工作。这是客户端的问题。
UploadedFile#getContentType()
返回客户端在多部分/表单数据部分的Content Type
头字段中发送的任何内容。显然,所讨论的客户端没有与上载文件的文件扩展名关联的任何mime类型。如果客户端未安装MS Excel,则可能发生这种情况
作为服务器,您还可以根据文件扩展名来确定mime类型,或者当您仍然使用古老的JSF 1.x时,通过
mime类型信息是从web.xml
中的
条目中获取的。servletcontainer在其默认的web.xml
中有一个完整的列表(例如,对于Tomcat,您可以在其/conf
文件夹中找到它)。您可以在webapp自己的web.xml
中对其进行扩展/覆盖,如下所示:
xlsx
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
请注意,此检测纯粹基于文件扩展名,而不是文件内容。因此,当客户端编辑了文件扩展名时,这并不能防止错误检测。最可靠的方法是使用真正的Excel文件解析器(如Apache POI或JExcelAPI)对其进行解析,并检查解析时是否引发异常。他们以前工作得很好-在什么之前?@pap我听说他们不久前工作得很好,但我刚刚开始处理该项目…我已经回答了如何修复它。毕竟,您不应该依赖特定于客户的数据。您也不应该期望您的所有网页访问者都安装了MS Office。愚蠢的错误,吸取的教训,咬紧牙关,现在就改正,下次再记住。可能发生:)祝你好运。
public class Parser {
public Parser() {
}
public String parse() {
//it should be 'application/vnd.ms-excel' type
//since i'm uploading an excel file saved in MS Excel 2007
System.err.print(uploadFile.getContentType());
// but its content-type is 'application/octet-stream'
return null;
}
public UploadedFile getUploadFile() {
return uploadFile;
}
public void setUploadFile(UploadedFile uploadFile) {
this.uploadFile = uploadFile;
}
}
String filename = FilenameUtils.getName(uploadedFile.getName()); // This is available by Commons IO which you should already have.
String mimetype = FacesContext.getCurrentInstance().getExternalContext().getMimeType(filename);
// ...