Problems with JSF Fileupload

Asked

Viewed 1,008 times

12

I am able to save the disk image in this JSF project

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">

<h:head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Titulo</title>
</h:head>

<h:form enctype="multipart/form-data">
    <p:fileUpload value="#{fileuploadBean.file}" mode="simple"
        update="growl" />
    <h:commandButton value="submit" action="#{fileuploadBean.imprimir}"
        actionListener="#{fileuploadBean.upload}" />
</h:form>
<h:form>
    <p:growl id="growl" showDetail="true" />
</h:form>

</html>

But when I test it on another page I cannot succeed, actually this page is linked to some attributes of an entity.

The pieces I’m having trouble with on this page are these;

        <p:outputLabel value="Foto do produto:" />
        <p:fileUpload value="#{fileuploadBean.file}" mode="simple" />

and that

            actionListener="#{fileuploadBean.upload}"

And this is the full page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">

<ui:composition template="/templates/modeloGeral.xhtml">
    <ui:define name="metadata">
        <f:metadata>
            <f:viewParam name="proacao" value="#{produtoBean.acao}" />
            <f:viewParam name="procod" value="#{produtoBean.codigo}" />
            <f:event listener="#{produtoBean.carregarCadastro}"
                type="preRenderView" />
        </f:metadata>
    </ui:define>


    <ui:define name="conteudo">
        <h:form id="frmFabCad"  enctype="multipart/form-data">
            <p:toolbar>
                <f:facet name="left">
                    <h:outputText value="Produto" />
                </f:facet>
            </p:toolbar>

            <h:panelGrid id="pnlProCadDados" columns="2">
                <p:outputLabel value="codigo" />
                <p:inputText size="10" readonly="true"
                    value="#{produtoBean.produtoCadastro.codigo}" />

                <p:outputLabel value="Descrição:" />
                <p:inputText maxlength="50" size="30"
                    value="#{produtoBean.produtoCadastro.descricao}"
                    readonly="#{produtoBean.acao == 'Excluir'}">
                    <f:validateBean />
                </p:inputText>

                <p:outputLabel value="Foto do produto:" />
                <p:fileUpload value="#{fileuploadBean.file}" mode="simple" />

                <p:outputLabel value="Preço:" />
                <p:inputText size="20" value="#{produtoBean.produtoCadastro.preco}"
                    readonly="#{produtoBean.acao == 'Excluir'}">
                    <f:validateBean />
                    <f:convertNumber minFractionDigits="2" locale="pt_BR" />
                </p:inputText>

                <p:outputLabel value="Quantidade:" />
                <p:inputText size="20"
                    value="#{produtoBean.produtoCadastro.quantidade}"
                    readonly="#{produtoBean.acao == 'Excluir'}">
                    <f:validateBean />
                </p:inputText>
                <p:outputLabel value="Fabricante" />
                <p:selectOneMenu value="#{produtoBean.produtoCadastro.fabricante}"
                    converter="fabricanteConverter">
                    <f:selectItem itemLabel="Selecione um fabricante" itemValue="" />
                    <f:selectItems value="#{produtoBean.listaFabricantes}"
                        var="fabricante" itemValue="#{fabricante}"
                        itemLabel="#{fabricante.descricao}" />
                    <f:validateBean />
                </p:selectOneMenu>



            </h:panelGrid>

            <h:panelGrid columns="5">
                <p:commandButton value="Novo" actionListener="#{produtoBean.novo}"
                    update=":frmFabCad:pnlProCadDados"
                    rendered="#{produtoBean.acao == 'Novo'}" />

                <p:commandButton value="Salvar"
                    action="#{produtoBean.salvar}"
                    actionListener="#{fileuploadBean.upload}"
                    update=":msgGlobal :frmFabCad:pnlProCadDados"
                    rendered="#{produtoBean.acao == 'Novo'}" />

                <p:commandButton value="Excluir"
                    actionListener="#{produtoBean.excluir}" update=":msgGlobal"
                    rendered="#{produtoBean.acao == 'Excluir'}" />

                <p:commandButton value="Editar"
                    actionListener="#{produtoBean.editar}" update=":msgGlobal"
                    rendered="#{produtoBean.acao == 'Editar'}" />

                <p:button value="Voltar" outcome="/pages/produtoPesquisa.xhtml" />
            </h:panelGrid>
        </h:form>
    </ui:define>

</ui:composition>
</html>

this is the mistake that comes when I press the save button

mai 20, 2015 4:54:25 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: /pages/produtoCadastro.xhtml @80,49 actionListener="#{fileuploadBean.upload}": java.lang.NullPointerException
javax.el.ELException: /pages/produtoCadastro.xhtml @80,49 actionListener="#{fileuploadBean.upload}": java.lang.NullPointerException
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    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.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at br.com.drogaria.bean.FileuploadBean.upload(FileuploadBean.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 35 more

mai 20, 2015 4:54:25 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: java.lang.NullPointerException
    at br.com.drogaria.bean.FileuploadBean.upload(FileuploadBean.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    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.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

I can’t understand why he can’t find my upload method.

This is my class Bean

package br.com.drogaria.bean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.fileupload.FileUpload;
import org.primefaces.model.UploadedFile;

@ManagedBean
@SessionScoped
public class FileuploadBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String destination = "C:\\tmp\\";
    private UploadedFile file;
    String extValidate;
    public FileuploadBean() {

    }

    public void imprimir() {
        System.out.println("testando essa aplicação");
    }

    public void TransferFile(String fileName, InputStream in) {
        try {
            OutputStream out = new FileOutputStream(new File(destination
                    + fileName));
            int reader = 0;
            byte[] bytes = new byte[(int) getFile().getSize()];
            while ((reader = in.read(bytes)) != -1) {
                out.write(bytes, 0, reader);
            }
            in.close();
            out.flush();

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }

    public void upload() {

        System.out.println("testando o upload");


        if (getFile() != null) {
            String ext = getFile().getFileName();
            if (ext != null) {
                extValidate = ext.substring(ext.indexOf(".") + 1);
            } else {
                extValidate = "null";
            }

            if (extValidate.equals("jpg") || extValidate.equals("png")) {
                try {
                    TransferFile(getFile().getFileName(), getFile()
                            .getInputstream());
                } catch (IOException ex) {

                    Logger.getLogger(FileUpload.class.getName()).log(
                            Level.SEVERE, null, ex);
                    FacesContext context = FacesContext.getCurrentInstance();
                    context.addMessage(null, new FacesMessage(
                            "Perigo, erro ao fazer Upload do arquivo"));
                }
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, new FacesMessage("Sucesso", getFile()
                        .getFileName()
                        + "seu upload. conteudo"
                        + getFile().getContentType()
                        + "tamanho"
                        + getFile().getSize()));

            } else {
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, new FacesMessage("Perigo",
                        "o arquivo tem que ser pdf"));

            }
        } else {

            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(
                    "Perigo, selecione o arquivo"));
        }

//      String nomeAquivo = "";
//      nomeAquivo = getFile().getFileName();

        System.out.println("valor da variavel getFile() "+getFile());
        // System.out.println(destination + "nome do arquivo" + " " +
        // nomeAquivo);

    }







    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

}

I found that he falls for that exception

Facescontext context = Facescontext.getCurrentInstance(); context.addMessage(null, new Facesmessage( "Danger, select the file")); }

On the successful getFile() page it results in this value

org.primefaces.model.NativeUploadedFile@56f1827b

But on the page that is having problem the value of getFile is Null

So how to fix this problem?

I made some changes before, because before he was making that mistake

 Caused by: javax.servlet.ServletException: org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8

So with a lot of research I found this post

https://stackoverflow.com/questions/19262356/file-upload-doesnt-work-with-ajax-in-primefaces-4-0-jsf-2-2-x-javax-servlet-s/19381134#19381134

And include that class

package br.com.drogaria.bean;

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) {

        if (context.getExternalContext().getRequestContentType().toLowerCase().startsWith("multipart/")) {
            super.decode(context, 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", SearchExpressionFacade.resolveComponentsForClient(context, fileUpload, 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", "function()", fileUpload.getOnerror())
                .callback("oncomplete", "function()", 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", clientId, "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, fileUpload, 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", null);
        writer.writeAttribute("class", 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, 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", null);
        writer.writeAttribute("class", cssClass, null);

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

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

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

        writer.endElement("span");
    }

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

        writer.startElement("input", null);
        writer.writeAttribute("type", "file", null);
        writer.writeAttribute("id", clientId, null);
        writer.writeAttribute("name", clientId, 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", null);
        writer.writeAttribute("type", "button", null);
        writer.writeAttribute("class", cssClass, null);
        writer.writeAttribute("disabled", "disabled", null);

        //button icon
        String iconClass = HTML.BUTTON_LEFT_ICON_CLASS;
        writer.startElement("span", null);
        writer.writeAttribute("class", iconClass + " " + icon, null);
        writer.endElement("span");

        //text
        writer.startElement("span", null);
        writer.writeAttribute("class", HTML.BUTTON_TEXT_CLASS, 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");
    }
}

After that started generating the current errors

is it because of this class that is making getFile Null?

  • Put your bean on so we can help you

  • Sorry, I just got an update on my post. If you can’t get help tell me, that I can give you more information, may be that with more information help you.

  • Take a look at my post update

  • 1

    face when performing the Istener use fileUploadListener and in its method public void seu metodo(FileUploadEvent event)

  • web.xml is set to upload? put the right libs?

  • I don’t know if it helps, but since the error is nullpointer. Probably something has not been processed, check the process

  • You managed to solve your problem?

Show 2 more comments

1 answer

1

Follow an example working using Fileupload with JSF 2.2 Some Vesses is easier to get a working code and replicate, than to find an error.

In view

<ui:composition template="/WEB-INF/template/LayoutPadrao.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:o="http://omnifaces.org/ui">

<p:commandButton rendered="#{cadastroCarroBean.carro.hasFoto()}" icon="ui-icon-extlink" title="Imagem" 
                        process="@this" oncomplete="PF('mostraImagem').show()" update=":frmCadastro:mostraImagemDialog">
                    <f:setPropertyActionListener target="#{fotoCarroBean.carroSelecionado}" value="#{cadastroCarroBean.carro}" />
                </p:commandButton>
                <p:fileUpload id="foto" value="#{cadastroCarroBean.fotoCarro}" mode="simple"/>
            </h:panelGroup>

<p:dialog id="mostraImagemDialog" header="Imagem" widgetVar="mostraImagem" modal="true" closeOnEscape="true">
            <p:graphicImage value="#{fotoCarroBean.foto}" cache="false" />
        </p:dialog>

The class Fotocarrobean

public class FotoCarroBean implements Serializable {

private static final long serialVersionUID = 1L;

private Carro carroSelecionado;

public StreamedContent getFoto() {
    DefaultStreamedContent content = null;
    if (this.carroSelecionado != null && this.carroSelecionado.getFoto() != null
            && this.carroSelecionado.getFoto().length > 0) {
        byte[] imagem = this.carroSelecionado.getFoto();
        content = new DefaultStreamedContent(new ByteArrayInputStream(imagem), "image/jpg", "carro.jpg");
    }

    return content;
}

public Carro getCarroSelecionado() {
    return carroSelecionado;
}

public void setCarroSelecionado(Carro carroSelecionado) {
    this.carroSelecionado = carroSelecionado;
}

}

Car entity

private byte[] foto;
 public boolean hasFoto() {
    return this.foto != null && this.foto.length > 0;
}

POM file has to have that of dependencies (I put the Hibernate, it may vary from version to version)

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <!-- Hibernate / JPA -->
    <hibernate.version>4.3.11.Final</hibernate.version>

    <!-- Omnifaces -->
    <omnifaces.version>2.1</omnifaces.version>

    <!-- Primefaces -->
    <primefaces.version>5.2</primefaces.version>

    <!-- JSF Version -->
    <javax.faces.version>2.2.10</javax.faces.version>

    <!-- Commons Fileupload -->
    <commons-fileupload.version>1.3.1</commons-fileupload.version>

    <!-- Commons Lang (utilidades) -->
    <commons-lang3.version>3.4</commons-lang3.version>
</properties>

Web.xml

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.