文件上传在PrimeFaces 4.0/JSF 2.2.x中不能与AJAX一起使用 – javax.servlet.ServletException:请求内容类型不是多部分/表单数据

前端之家收集整理的这篇文章主要介绍了文件上传在PrimeFaces 4.0/JSF 2.2.x中不能与AJAX一起使用 – javax.servlet.ServletException:请求内容类型不是多部分/表单数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
重要提示:此主题中讨论的问题在2014年10月6日星期一(从几分钟前开始)的 PrimeFaces 5.1 final(社区发布) released已经是 fixed。我试图在 JSF 2.2.8-02(或 apiimpl)。 @H_301_1@因此,如果你碰巧使用该版本(或更高版本,无需提及),你甚至不需要再读这个问题。

@H_301_1@我有一个web应用程序运行

@H_301_1@> GlassFish 4.0
> Mojarra 2.2.4
> PrimeFaces 4.0 final

@H_301_1@除了用AJAX文件上传之外的所有东西都很好。以下xhtml文件通过由PrimeFaces命令按钮触发的AJAX请求发送多部分内容

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:p="http://primefaces.org/ui"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Test</title>
    </h:head>
    <h:body>
        <h:form prependId="true" enctype="multipart/form-data">
            <p:fileUpload id="txtCatImage"
                          value="#{testManagedBean.uploadedFile}"
                          mode="advanced"
                          dragDropSupport="true"
                          fileLimit="1"
                          sizeLimit="100000"
                          multiple="false"
                          allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
                          fileUploadListener="#{testManagedBean.fileUploadListener}"/>

            <p:message for="txtCatImage" showSummary="false"/>
            <p:commandButton id="btnSubmit" 
                             actionListener="#{testManagedBean.insert}" 
                             ajax="true" icon="ui-icon-check" value="Save"/>                
        </h:form>
    </h:body>
</html>
@H_301_1@测试托管bean:

@ManagedBean
@ViewScoped
public final class TestManagedBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private UploadedFile uploadedFile;

    public TestManagedBean(){}

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

    public void fileUploadListener(FileUploadEvent event){
        uploadedFile=event.getFile();
    }

    public void insert(){
        if(uploadedFile!=null){
            System.out.println(uploadedFile.getFileName());
        }
        else{
            System.out.println("The file object is null.");
        }
    }
}
@H_301_1@当文件文件浏览上传时,它在其监听器 – fileUploadListener()中显示文件名。

@H_301_1@上传文件后,当按下给定的命令按钮(ajax =“true”)时,会导致抛出以下异常。

WARNING:   javax.servlet.ServletException: The request content-type is not a multipart/form-data
javax.faces.FacesException: javax.servlet.ServletException: The request content-type is not a multipart/form-data
    at org.primefaces.component.fileupload.NativeFileUploadDecoder.decode(NativeFileUploadDecoder.java:44)
    at org.primefaces.component.fileupload.FileUploadRenderer.decode(FileUploadRenderer.java:44)
    at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:831)
    at javax.faces.component.UIInput.decode(UIInput.java:771)
    at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1225)
    at javax.faces.component.UIInput.processDecodes(UIInput.java:676)
    at javax.faces.component.UIForm.processDecodes(UIForm.java:225)
    at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1220)
    at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1220)
    at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:929)
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at filter.NoCacheFilter.doFilter(NoCacheFilter.java:28)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadioStrategy.run0(WorkerThreadioStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadioStrategy.access$100(WorkerThreadioStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadioStrategy$WorkerThreadRunnable.run(WorkerThreadioStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:722)
Caused by: javax.servlet.ServletException: The request content-type is not a multipart/form-data
    at org.apache.catalina.fileupload.Multipart.getPart(Multipart.java:187)
    at org.apache.catalina.connector.Request.getPart(Request.java:4535)
    at org.apache.catalina.connector.RequestFacade.getPart(RequestFacade.java:1095)
    at org.primefaces.component.fileupload.NativeFileUploadDecoder.decodeAdvanced(NativeFileUploadDecoder.java:60)
    at org.primefaces.component.fileupload.NativeFileUploadDecoder.decode(NativeFileUploadDecoder.java:37)
    ... 48 more

SEVERE:   javax.servlet.ServletException: The request content-type is not a multipart/form-data
    at org.apache.catalina.fileupload.Multipart.getPart(Multipart.java:187)
    at org.apache.catalina.connector.Request.getPart(Request.java:4535)
    at org.apache.catalina.connector.RequestFacade.getPart(RequestFacade.java:1095)
    at org.primefaces.component.fileupload.NativeFileUploadDecoder.decodeAdvanced(NativeFileUploadDecoder.java:60)
    at org.primefaces.component.fileupload.NativeFileUploadDecoder.decode(NativeFileUploadDecoder.java:37)
    at org.primefaces.component.fileupload.FileUploadRenderer.decode(FileUploadRenderer.java:44)
    at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:831)
    at javax.faces.component.UIInput.decode(UIInput.java:771)
    at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1225)
    at javax.faces.component.UIInput.processDecodes(UIInput.java:676)
    at javax.faces.component.UIForm.processDecodes(UIForm.java:225)
    at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1220)
    at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1220)
    at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:929)
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at filter.NoCacheFilter.doFilter(NoCacheFilter.java:28)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadioStrategy.run0(WorkerThreadioStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadioStrategy.access$100(WorkerThreadioStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadioStrategy$WorkerThreadRunnable.run(WorkerThreadioStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:722)
@H_301_1@它只能在命令按钮的ajax属性设置为false – ajax =“false”时工作。

@H_301_1@我已经将Mojarra版本降级到2.1.9在Tomcat 7.0.35。它与这个Mojarra版本以及PrimeFaces 4.0 final(和PrimeFaces 4.0 RC1)一起工作 – 用AJAX请求上传文件

@H_301_1@我替换尝试了下面的Mojarra版本

@H_301_1@> 2.2.0
> 2.2.1
> 2.2.2
> 2.2.3
> 2.2.4

@H_301_1@在GlassFish 4.0中,但没有一个成功上传文件与AJAX请求,这是非常需要的,因为使用< p:rowEditor /> (例如,在每一行中的图像)在PrimeFaces DataTable总是基于AJAX。

@H_301_1@我想保持GlassFish 4.0无论如何。我也试图降级Mojarra 2.1.9在GlassFish 4.0,但它无法创建捆绑以异常结束。 GlassFish 4.0似乎不适合Mojarra低于2.2.x.

@H_301_1@那么,什么是造成此异常的原因 – PrimeFaces或JSF?只是困惑。在此给定环境中是否有任何解决方法上传具有AJAX请求的文件

@H_301_1@编辑:

@H_301_1@web.xml中的过滤器映射:

<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
@H_301_1@问题仍然与Mojarra版本2.2.5(或apiimpl)released在2014年1月8日保持不变。

@H_301_1@再次尝试Mojarra版本2.2.6(或apiimpl)released在2014年3月4日。问题保持不变。

@H_301_1@仍然不工作在PrimeFaces 5.0最后released年5月05日。

我遇到过同样的问题。它似乎更关系到< p:commandButton>比< p:fileUpload>组件,因为它与< h:commandButton> (甚至与ajax)。 @H_301_1@你可以尝试:

<h:commandButton id="btnSubmit" actionListener="#{testManagedBean.insert}" value="Save">
    <f:ajax execute="@all" render="@form"/>
</h:commandButton>
@H_301_1@我不能告诉你为什么或如何工作,但它解决了我的问题。
当然的缺点是,你必须自己做造型,至少直到
Primefaces的家伙解决这个问题。

@H_301_1@编辑:

@H_301_1@在挖掘源代码,并做一些调试,如果弄清楚,实际上有两个请求(我尝试在< p:wizard />)。第一个是multipart / form-data,它实际上完成文件上传。它触发Bean中的fileUploadEvent。我的向导的下一个按钮是按下另一个形式用enctype application / www-urlencoded提交的。这导致异常。结论是,不同于我在注释中所写的抑制异常是一个有效的解决方案。这甚至可以以不包括改变Primefaces.jar的方式完成,如果家伙在未来的版本中解决这个问题,这是方便的。

@H_301_1@所以这里是需要做的:

@H_301_1@>创建一个新类com.yourpackage.fileupload.FileUploadRenderer
>将以下代码复制并粘贴到新类中:

package com.yourpackage.fileupload.fileupload;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.component.fileupload.CommonsFileUploadDecoder;
import org.primefaces.component.fileupload.FileUpload;
import org.primefaces.component.fileupload.NativeFileUploadDecoder;
import org.primefaces.config.ConfigContainer;
import org.primefaces.context.RequestContext;
import org.primefaces.expression.SearchExpressionFacade;
import org.primefaces.renderkit.CoreRenderer;
import org.primefaces.util.HTML;        
import org.primefaces.util.WidgetBuilder;

public class FileUploadRenderer extends CoreRenderer {

    @Override
    public void decode(FacesContext context,UIComponent component) {
        FileUpload fileUpload = (FileUpload) component;

        if (!fileUpload.isDisabled()) {
            ConfigContainer cc = RequestContext.getCurrentInstance().getApplicationContext().getConfig();
            String uploader = cc.getUploader();
            boolean isAtLeastJSF22 = cc.isAtLeastJSF22();

            if (uploader.equals("auto")) {
                if (isAtLeastJSF22) {
                    if (isMultiPartRequest(context)) {
                        NativeFileUploadDecoder.decode(context,fileUpload);
                    }
                } else {
                    CommonsFileUploadDecoder.decode(context,fileUpload);
                }
            } else if (uploader.equals("native")) {
                if (!isAtLeastJSF22) {
                    throw new FacesException("native uploader requires at least a JSF 2.2 runtime");
                }

                NativeFileUploadDecoder.decode(context,fileUpload);
            } else if (uploader.equals("commons")) {
                CommonsFileUploadDecoder.decode(context,fileUpload);
            }
        }
    }

    @Override
    public void encodeEnd(FacesContext context,UIComponent component) throws IOException {
        FileUpload fileUpload = (FileUpload) component;

        encodeMarkup(context,fileUpload);

        if (fileUpload.getMode().equals("advanced")) {
            encodeScript(context,fileUpload);
        }
    }

    protected void encodeScript(FacesContext context,FileUpload fileUpload) throws IOException {
        String clientId = fileUpload.getClientId(context);
        String update = fileUpload.getUpdate();
        String process = fileUpload.getProcess();
        WidgetBuilder wb = getWidgetBuilder(context);
        wb.initWithDomReady("FileUpload",fileUpload.resolveWidgetVar(),clientId,"fileupload");

        wb.attr("auto",fileUpload.isAuto(),false)
                .attr("dnd",fileUpload.isDragDropSupport(),true)
                .attr("update",SearchExpressionFacade.resolveComponentsForClient(context,fileUpload,update),null)
                .attr("process",process),null)
                .attr("maxFileSize",fileUpload.getSizeLimit(),Long.MAX_VALUE)
                .attr("fileLimit",fileUpload.getFileLimit(),Integer.MAX_VALUE)
                .attr("invalidFileMessage",fileUpload.getInvalidFileMessage(),null)
                .attr("invalidSizeMessage",fileUpload.getInvalidSizeMessage(),null)
                .attr("fileLimitMessage",fileUpload.getFileLimitMessage(),null)
                .attr("messageTemplate",fileUpload.getMessageTemplate(),null)
                .attr("previewWidth",fileUpload.getPreviewWidth(),80)
                .attr("disabled",fileUpload.isDisabled(),false)
                .callback("onstart","function()",fileUpload.getOnstart())
                .callback("onerror",fileUpload.getOnerror())
                .callback("oncomplete",fileUpload.getOncomplete());

        if (fileUpload.getAllowTypes() != null) {
            wb.append(",allowTypes:").append(fileUpload.getAllowTypes());
        }

        wb.finish();
    }

    protected void encodeMarkup(FacesContext context,FileUpload fileUpload) throws IOException {
        if (fileUpload.getMode().equals("simple")) {
            encodeSimpleMarkup(context,fileUpload);
        } else {
            encodeAdvancedMarkup(context,fileUpload);
        }
    }

    protected void encodeAdvancedMarkup(FacesContext context,FileUpload fileUpload) throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        String clientId = fileUpload.getClientId(context);
        String style = fileUpload.getStyle();
        String styleClass = fileUpload.getStyleClass();
        styleClass = styleClass == null ? FileUpload.CONTAINER_CLASS : FileUpload.CONTAINER_CLASS + " " + styleClass;
        boolean disabled = fileUpload.isDisabled();

        writer.startElement("div",fileUpload);
        writer.writeAttribute("id","id");
        writer.writeAttribute("class",styleClass,styleClass);
        if (style != null) {
            writer.writeAttribute("style",style,"style");
        }

        //buttonbar
        writer.startElement("div",fileUpload);
        writer.writeAttribute("class",FileUpload.BUTTON_BAR_CLASS,null);

        //choose button
        encodeChooseButton(context,disabled);

        if (!fileUpload.isAuto()) {
            encodeButton(context,fileUpload.getUploadLabel(),FileUpload.UPLOAD_BUTTON_CLASS,"ui-icon-arrowreturnthick-1-n");
            encodeButton(context,fileUpload.getCancelLabel(),FileUpload.CANCEL_BUTTON_CLASS,"ui-icon-cancel");
        }

        writer.endElement("div");

        //content
        writer.startElement("div",null);
        writer.writeAttribute("class",FileUpload.CONTENT_CLASS,null);

        writer.startElement("table",FileUpload.FILES_CLASS,null);
        writer.startElement("tbody",null);
        writer.endElement("tbody");
        writer.endElement("table");

        writer.endElement("div");

        writer.endElement("div");
    }

    protected void encodeSimpleMarkup(FacesContext context,FileUpload fileUpload) throws IOException {
        encodeInputField(context,fileUpload.getClientId(context));
    }

    protected void encodeChooseButton(FacesContext context,FileUpload fileUpload,boolean disabled) throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        String clientId = fileUpload.getClientId(context);
        String cssClass = HTML.BUTTON_TEXT_ICON_LEFT_BUTTON_CLASS + " " + FileUpload.CHOOSE_BUTTON_CLASS;
        if (disabled) {
            cssClass += " ui-state-disabled";
        }

        writer.startElement("span",cssClass,null);

        //button icon 
        writer.startElement("span",HTML.BUTTON_LEFT_ICON_CLASS + " ui-icon-plusthick",null);
        writer.endElement("span");

        //text
        writer.startElement("span",HTML.BUTTON_TEXT_CLASS,null);
        writer.writeText(fileUpload.getLabel(),"value");
        writer.endElement("span");

        if (!disabled) {
            encodeInputField(context,clientId + "_input");
        }

        writer.endElement("span");
    }

    protected void encodeInputField(FacesContext context,String clientId) throws IOException {
        ResponseWriter writer = context.getResponseWriter();

        writer.startElement("input",null);
        writer.writeAttribute("type","file",null);
        writer.writeAttribute("id",null);
        writer.writeAttribute("name",null);

        if (fileUpload.isMultiple()) {
            writer.writeAttribute("multiple","multiple",null);
        }
        if (fileUpload.getStyle() != null) {
            writer.writeAttribute("style",fileUpload.getStyle(),"style");
        }
        if (fileUpload.getStyleClass() != null) {
            writer.writeAttribute("class",fileUpload.getStyleClass(),"styleClass");
        }
        if (fileUpload.isDisabled()) {
            writer.writeAttribute("disabled","disabled","disabled");
        }

        writer.endElement("input");
    }

    protected void encodeButton(FacesContext context,String label,String styleClass,String icon) throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        String cssClass = HTML.BUTTON_TEXT_ICON_LEFT_BUTTON_CLASS + " ui-state-disabled " + styleClass;

        writer.startElement("button","button",null);
        writer.writeAttribute("disabled",null);

        //button icon
        String iconClass = HTML.BUTTON_LEFT_ICON_CLASS;
        writer.startElement("span",iconClass + " " + icon,null);
        writer.writeText(label,"value");
        writer.endElement("span");
        writer.endElement("button");
    }

    private boolean isMultiPartRequest(FacesContext context) {
        if (context == null) {
            return false;
        }

        return ((HttpServletRequest) context.getExternalContext().getRequest()).getContentType().startsWith("multipart");
    }
}
@H_301_1@>在faces-config.xml底部添加以下行:

<render-kit>
    <renderer>
        <component-family>org.primefaces.component</component-family>
        <renderer-type>org.primefaces.component.FileUploadRenderer</renderer-type>
        <renderer-class>com.yourpackage.fileupload.FileUploadRenderer</renderer-class>
    </renderer>
</render-kit>
@H_301_1@>你准备好了!

@H_301_1@我们做了什么?我们创建了自己的FileUploadRenderer,它使用方法isMultiPartRequest()检查contentType是否为multipart / form-data。只有当这返回true,其余的代码才被执行。在任何其他情况下,不会发生任何事情,这意味着不会抛出异常。如果Primefaces修复了这个问题,你只需要删除你的faces-config.xml中的行以使用他们的类。

@H_301_1@让我知道如果这是为你工作!

@H_301_1@编辑

@H_301_1@此代码检查给定的请求是否是multipart / form-data类型。如果不是,则停止执行。原来的Primefaces代码仍然会继续。正如我上面提到的,如果你在Primefaces组件中上传一个文件,实际上有两个请求:

@H_301_1@>使用< p:fileUpload />的Ajax-FileUpload (enctype:multipart / form-data)
>< p:editRow />中的Ajax操作或< p:wizard /> (enctype:application / www-form-urlencoded)

@H_301_1@第一个由渲染器处理,而第二个引起原始代码中的异常,因为渲染器尝试处理它不能够处理的东西。使用代码中所做的更改,只有multipart / form-data表单由渲染器处理,所以不会发生异常。 IMO显然是Primefaces的一个bug。代码差异只是方法private boolean isMultiPartRequest(FacesContext context)和它在代码中出现一次。很高兴我可以帮助你!

猜你在找的Ajax相关文章