0

I searched and tried every example on web that i found but my example still doesn't work. My web.xml

...(headers)

<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>
<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>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<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>
<listener>
    <listener-class>registration.cleanRegisterDB</listener-class>
</listener>
<listener>
    <listener-class>main.poolChecker</listener-class>
</listener>
<session-config>
    <session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<listener>
    <listener-class>Utils.SessionAtributeListener.MyAtributeListener</listener-class>
</listener>
<context-param>
    <param-name>primefaces.PRIVATE_CAPTCHA_KEY</param-name>
    <param-value>...</param-value>
</context-param>
<context-param>
    <param-name>primefaces.PUBLIC_CAPTCHA_KEY</param-name>
    <param-value>...</param-value>
</context-param>
<error-page>
    <error-code>404</error-code>
    <location>/faces/404.xhtml</location>
</error-page>

My xhtml page:

<?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 
lang="#{main_bean.authLang()}"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">

<f:view locale="#{main_bean.locale}" encoding="ISO-8859-1" >
    <h:head>            
        <h:outputStylesheet library="theme1" name="css/style.css"/>
        <h:outputScript library="theme1" name="js/jquery.validate.js"/>
    </h:head>

    <h:body> 
        <f:event type="preRenderComponent" listener="#{postbean.loadMasterCategories()}" ></f:event>
        <h:panelGroup id="layout-for-image" layout="block">
            <h:link outcome="index.xhtml?faces-redirect=true">
                <h:graphicImage name="theme1/images/logo.png" />
            </h:link>
        </h:panelGroup>

        <h:panelGroup class="layout-titles" layout="block">
            <h2>#{msg.postInt}</h2>
        </h:panelGroup>
        <h:form id="formPostpool" enctype="multipart/form-data" >
            <p:growl id="growlaa" autoUpdate="true"/>
            <p:confirmDialog id="confirmDialog" message="#{msg.dialogConfPostInt}"  
                             header="#{msg.confirmDialogHeader}" severity="alert" widgetVar="confirmation" >  
                <h:panelGroup id="dialog-captcha-layout" layout="block" > 
                    <h:panelGroup layout="block" style="display: inline-block; *display: inline; zoom: 1;">
                        <p:captcha label="Captcha" validatorMessage="#{msg.invalidCaptcha}" required="true" requiredMessage="#{msg.CaptchaNull}" language="#{main_bean.authLang()}"/>
                    </h:panelGroup>
                </h:panelGroup>

                <p:commandButton id="confirm" styleClass="h-button-search" icon="iconDialogYes" actionListener="#{captchaBean.submit}"
                                 action="index" ajax="false" onclick="confirmation.hide();" style="background-image: url('../resources/theme1/images/icons/yes.png')" >
                    <f:actionListener binding="#{postbean.publicatePool()}" />
                </p:commandButton>

                <p:commandButton id="notconfirm" styleClass="h-button-search" icon="iconDialogNo"
                                 ajax="false" type="button" onclick="confirmation.hide();"/> 
            </p:confirmDialog>

            <h:panelGroup class="layout-item-details" layout="block">
                <h2>#{msg.infoProd}</h2>
                <h:panelGroup class="details-element" layout="block">
                    <h:outputLabel value="#{msg.categoryPost}" for="cat"/>
                    <h:panelGroup class="element-inputs" layout="block">
                        <p:selectOneListbox style="height: 150px;" id="cat" value="#{postbean.masterCategoria}" converter="omnifaces.SelectItemsConverter" required="true" requiredMessage="#{msg.message_radiobutton_choose}">
                            <f:selectItems value="#{postbean.categorias}" var="cat" itemLabel="#{cat.descricao}" itemValue="#{cat}" />
                        </p:selectOneListbox>  

                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.titlePost}" for="titulo"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="titulo" value="#{postbean.titulo}" styleClass="inputs-login" required="true" requiredMessage="#{msg.message_titulo_null}"/>
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.descricaoPost}" for="desc"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputTextarea id="desc" value="#{postbean.descricao}" rows="6" cols="70" styleClass="inputs-textarea" required="true" requiredMessage="#{msg.message_descricao_null}"/>
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.marcaPost}" for="marca"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="marca" value="#{postbean.marca}" styleClass="inputs-login" />
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.modeloPost}" for="Modelo"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="Modelo" value="#{postbean.modelo}" styleClass="inputs-login" />
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.quantidadePost}" for="qtdDesejada"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="qtdDesejada" value="#{postbean.quantidadePretendida}" styleClass="inputs-login" style="width: 100px !important;" required="true" requiredMessage="#{msg.message_quantidade_null}" validatorMessage="#{msg.message_quantidade_invalid}">
                            <f:validateDoubleRange minimum="0.00000001" />
                            <!--<f:validateRegex pattern="([1-9][0-9]*\.?[0-9]*)" for="qtdDesejada" />-->
                        </p:inputText>
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.precoTargetPost}" for="precoTarget"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="precoTarget" value="#{postbean.preco}" styleClass="inputs-login" style="width: 100px !important;" required="true" requiredMessage="#{msg.message_precoTarget_null}" validatorMessage="#{msg.message_precoTarget_invalid}">
                            <f:validateDoubleRange minimum="0.00000001" />
                        </p:inputText>
                    </h:panelGroup>
                </h:panelGroup>
                <h:panelGroup class="details-element" layout="block">

                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.fotosPost}" for="foto"/>
                    </h:panelGroup>
                    <!--                        <h:panelGroup layout="block" style="display: inline-block; *display: inline; zoom: 1;" id="addFotoPanel">
                                                <h:inputFile id="idinputFile" value="#{postbean.file}" />
                                            </h:panelGroup>-->
                    <p:fileUpload value="#{postbean.upfile}" auto="true"  fileUploadListener="#{postbean.handleFileUpload}" widgetVar="asd" />

                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block" style="margin-bottom: 15px; width: 250px; padding-left: 175px;">
                    <p:commandButton  id="btn" value="#{msg.label_buttonsubmit}" styleClass="h-button-search" onclick="confirmation.show();"/>
                </h:panelGroup>
            </h:panelGroup>

            <script type="text/javascript">
                                     $(document).ready(function() {
                                         $('#formPostpool').keypress(function(e) {
                                             if (e.keyCode == 13) {
                                                 event.preventDefault();
                                                 $("#btn").click();
                                             }
                                         })
                                     });
            </script>
        </h:form>
    </h:body>
</f:view>

And the bean: //...some imports

@ManagedBean(name = "postbean")
@ViewScoped
public class postbean implements Serializable {

//////////////////////////////////
//  FACADES
/////////////////////////////////
@EJB
ProdutoFacade produtofacade = new ProdutoFacade();
@EJB
UsersFacade userfacade = new UsersFacade();
@EJB
ImageFacade imagefacade = new ImageFacade();
@EJB
categoriasFacade categoriafacade = new categoriasFacade();
@EJB
buyerPoolFacade buyerPoolFacade = new buyerPoolFacade();
@EJB
LanguageFacade languageFacade = new LanguageFacade();
@EJB
Lingua_ProdutoFacade langProFacade = new Lingua_ProdutoFacade();
@EJB
MessagesFacade messagesFacade = new MessagesFacade();
/////////////////////////////////////
// VARIAVEIS
////////////////////////////////////
//Destino onde vão ser guardadas as imagens relativas a pool
private String destination = "C:";
private List<String> urls;
private String titulo;
private String descricao;
private String marca;
private String modelo;
private float preco;
private short estado;
private int quantidadePretendida;
private List<categorias> categoria; // lista das categorias
private Timestamp dataActual;
private Users publicationUser;
private categorias masterCategoria;
private categorias option2;
private List<categorias> text;
private List<categorias> subcat2;
private boolean rend;
private boolean rend2;
private Part file;
private UploadedFile upfile;

public Part getFile() {
    return file;
}

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

public UploadedFile getUpfile() {
    return upfile;
}

public void setUPfile(UploadedFile upfile) {
    this.upfile = upfile;
}

public postbean() {...}

//...getters and setters

//...some methods

public void handleFileUpload(FileUploadEvent event) {

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    FacesContext ctx = FacesContext.getCurrentInstance();
    Locale l = ctx.getViewRoot().getLocale();
    ResourceBundle rb = ResourceBundle.getBundle("languages.welcome", l);

    FacesContext aFacesContext = FacesContext.getCurrentInstance();
    ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
    try {
        copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        FacesMessage msg = new FacesMessage(rb.getString("Success"), event.getFile().getFileName() + rb.getString("wasUploaded"));
        FacesContext.getCurrentInstance().addMessage(null, msg);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void copyFile(String fileName, InputStream in) {
    String username = userfacade.findUserByIDSessao(FacesUtils.getSessionID());
    OutputStream out = null;
    try {
        // write the inputStream to a FileOutputStream
        File dir = new File(destination + username);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File f = new File(dir + "\\" + fileName);
        out = new FileOutputStream(f);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = in.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        urls.add(username + "//" + f.getName());

        System.out.println("New file created!");
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            in.close();
            out.flush();
            out.close();
        } catch (IOException ex) {
        }
    }
}
//..some methods
}

Well, I changed parameters, I removed the filter from web.xml file, I changed the bean... I know I've got to have a "multipart/form-data" form, a filter in web.xml file and a fileUploader to receive the event in the bean. However nothing is triggered. I click to choose and then to upload (if parameter is not auto="true") and nothing happens. I do have commons-io-2.4, commons-fileupload-1.3, primefaces-3.5 and I use GlassFish Server 4. Thank you!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Pedro Mendes
  • 1
  • 1
  • 3
  • 1
    Wow, what a code dump. Is for example the `private String descricao;` line absolutely necessary in order to reproduce the problem? I.e. when you remove it, then the whole problem is solved? No? Then just leave out that line! Do the same for all those other 1000 lines in your code. You should post only the **smallest possible but complete** code snippet which still reproduces the problem when copypasted unmodified into a completely blank playground project. – BalusC Aug 26 '13 at 23:47
  • Hi! I dumped it because i was/am trying to give information enough to trying to solve the question. As I said I tried to solve it in many ways but nothing... Answering your question, it is necessary because this example is to allow users to create new products. Before I write it, I saw your solution and tried to put it in a separated bean with only the `handleFileUpload(FileUploadEvent event)` method and another page with only `` but nothing... Thank you for your answer, @BalusC! – Pedro Mendes Aug 27 '13 at 11:48
  • You should post *that* information and code instead. Once you get that small unit of work to work based on the answers, then you can just simply extrapolate/substitute into the final code. A lot of answerers are not interested in facing a "wall of code" because of potential red herrings which may creep in. Forest, tree, you know. On the other hand, "wall of code" also signifies lack of *basic understanding* of the problem by the asker. This is then more likely to end up in chameleonization (endless editing) of question/answer which is totally beyond the point of this site. – BalusC Aug 27 '13 at 11:50
  • Thank you once more. I didn't realized it could be "too much info" and, as you said, it could get away answerers. I accept that critic. I put all that code because there are some details that could be essential. Hoping not to be boring, can you see more errors or can you give more solutions? I'm desperate. Thank you once more. – Pedro Mendes Aug 27 '13 at 12:16

2 Answers2

0
**Note:if you are using Spring-web-flow then it will work**  
 My web.xml file
 *Add this Configuration in web.xml file**

            <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>Spring MVC Dispatcher Servlet</servlet-name>
                </filter-mapping>

                <servlet>
                    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
                    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-    class>
                    <init-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value></param-value>
                    </init-param>
                    <load-on-startup>2</load-on-startup>
                </servlet>

                <servlet-mapping>
                    <servlet-name>Spring MVC Dispatcher Servlet</servlet- name>
                    <url-pattern>/spring/*</url-pattern>
                </servlet-mapping>

Fileupload.xhtml

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

 <p:fileUpload id="image"
 fileUploadListener="#{loadFileForm.handleFileUpload}"
mode="advanced" dragDropSupport="true" multiple="true"
update="messages" sizeLimit="100000" fileLimit="3"
allowTypes="/(\.|\/)(xls)$/" />
<p:growl id="messages" showDetail="true" />
</html>

LoadFileBean.java

@ManagedBean(name = "loadFileForm") public class LoadFileFormBean implements Serializable {

/**
 * handleFileUpload
 * @param event
 */
public void handleFileUpload(FileUploadEvent event) {
    FacesMessage msg = new FacesMessage("Succesful", event.getFile()
            .getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);
}
Pravin
  • 103
  • 1
  • 14
0

I haven't tried GlassFish but found that using PrimeFaces 4 on WebLogic we had to add this parameter to the web.xml:

<context-param>
    <param-name>primefaces.UPLOADER</param-name>
    <param-value>commons</param-value>
</context-param>

We're using this Maven dependency:

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
</dependency>

We also had to make sure that the PrimeFaces FileUpload Filter was the first filter entry in the web.xml. But it looks like yours is already.

Also, the file upload should have a form of its own.

awilkinson
  • 1,601
  • 15
  • 23