Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 上载excel文件时,内容类型不符合预期_Java_Jsf_Tomahawk - Fatal编程技术网

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);
// ...