Primefaces文件上传监听器不起作用。

4

我尝试使用Primefaces将文件上传到我的Tomcat7服务器。我正在使用Primefaces4。文件上传监听器未调用handleFileUpload,控制台中未出现hiii。 我的bean如下:

package Pin;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;

import org.primefaces.component.fileupload.FileUpload;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import Util.U;
@ManagedBean(name="pinBean")
@SessionScoped
public class PinBean{
    private UploadedFile file;
    public PinBean(){

        U.wl("Start");
    }
    public UploadedFile getFile() {
        U.wl("get");
        return file;
    }

    public void setFile(UploadedFile file) {
        U.wl("set");
        this.file = file;
    }
    public void handleFileUpload(FileUploadEvent event) {
        UploadedFile file = event.getFile();
        U.wl("hiii");
        //application code
        }


}

我的 XHTML 代码如下:

<?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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:t="http://myfaces.apache.org/tomahawk"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:p="http://primefaces.org/ui">

<h:form>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{pinBean.handleFileUpload}" auto="true" mode="advanced"/>
</h:form>
</h:form>
</html>

还有web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>testUpload</display-name>
  <filter>

<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>2097152</param-value>
</init-param>     
</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>/faces/*</url-pattern>
</servlet-mapping>
</web-app>

如何使用PrimeFaces p:fileUpload?监听器方法从未被调用。 - Tiny
2个回答

4

最终成功了,我使用了简单类型的上传。

重要事项:

1- 必须有 <h:head></h:head>

2- 在 web.xml 中必须这样设置:

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

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

3- 在 h:form 中,重要的是要写上 enctype="multipart/form-data"

4- 对于命令按钮,需要加上 ajax="false"

我使用了简单上传类型:

<?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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:t="http://myfaces.apache.org/tomahawk"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{pinBean.file}" mode="simple" />
<p:commandButton value="Submit" ajax="false"/>
</h:form>

</html>

我的Java Bean是:

package Pin;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;

import org.primefaces.component.fileupload.FileUpload;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import Util.U;
@ManagedBean(name="pinBean")
@SessionScoped
public class PinBean{
    private UploadedFile file;
    public PinBean(){

        U.wl("Start");
    }
    public UploadedFile getFile() {
        U.wl("get");
        return file;
    }

    public void setFile(UploadedFile file) {
        U.wl("set");
            this.file = file;
        }
}

以及我的web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>WebOffice</display-name>
  <context-param>
    <param-name>primefaces.UPLOADER</param-name>
    <param-value>commons</param-value>
  </context-param>

 <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>/faces/*</url-pattern>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <description>
    This parameter tells MyFaces if javascript code should be allowed in
    the rendered HTML output.
    If javascript is allowed, command_link anchors will have javascript code
    that submits the corresponding form.
    If javascript is not allowed, the state saving info and nested parameters
    will be added as url parameters.
    Default is 'true'</description>
    <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <description>
    If true, rendered HTML code will be formatted, so that it is 'human-readable'
    i.e. additional line separators and whitespace will be written, that do not
    influence the HTML code.
    Default is 'true'</description>
    <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
    <param-value>false</param-value>
  </context-param>
  <context-param>
    <description>
    If true, a javascript function will be rendered that is able to restore the
    former vertical scroll on every request. Convenient feature if you have pages
    with long lists and you do not want the browser page to always jump to the top
    if you trigger a link or button action that stays on the same page.
    Default is 'false'
</description>
    <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
    <param-value>true</param-value>
  </context-param>
  <listener>
    <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
  </listener>

  <context-param>
    <param-name>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</param-name>
    <param-value>false</param-value>
  </context-param>

  <filter>
    <filter-name>Filters</filter-name>
    <filter-class>UserManagement.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>Filters</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
    <error-page>
        <error-code>404</error-code>
        <location>/not_exist.jsf</location>
    </error-page>

    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/exception.jsf</location>
    </error-page>
</web-app>

1

做这件事是因为我以前也遇到了同样的问题

public void handleFileUpload(FileUploadEvent event) {

    System.out.println("calling file upload...");
    File targetFolder = new File(Properties.File_Uploaded_path

    + File.separator);

    if (!targetFolder.exists()) {
        targetFolder.mkdirs();
    }
    try {
        InputStream inputStream = event.getFile().getInputstream();

        OutputStream out = new FileOutputStream(new File(targetFolder,
                event.getFile().getFileName()));

        int read = 0;

        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {

            out.write(bytes, 0, read);

        }
        inputStream.close();
        out.flush();
        out.close();

    } catch (IOException e) {

        e.printStackTrace();
    }
    System.out.println("file upload after catch..");
    employeeFileUploadPaths[employeeFileCount] = targetFolder
            .getAbsolutePath()
            + File.separator
            + event.getFile().getFileName();
    System.out.println("empFileUploadPaths[check]"
            + employeeFileUploadPaths[employeeFileCount]);
    employeeFileCount++;

    FacesMessage msg = new FacesMessage("Succesful", event.getFile()
            .getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);
    System.out.println("last line of file upload....");
}

在XHTML页面中:
      <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!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:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:p="http://primefaces.org/ui">

    <h:head>
    </h:head>
    <h:body>
        <h:form enctype="multipart-data">
        <p:fileUpload fileUploadListener="#{employeeBean.handleFileUpload}"
                        required="true" mode="advanced" dragDropSupport="false"
                        multiple="true" sizeLimit="1000000" fileLimit="5" update="messages"
                        allowTypes="/(\.|\/)(gif|jpe?g|png|pdf|doc|docx)$/">
                        <p:growl id="messages" showDetail="true" />
                    </p:fileUpload>


                    <f:facet name="footer">
                        <p:commandButton value="Add" ajax="false"
                            action="#{employeeBean.addEmployee}">

                        </p:commandButton>
                    </f:facet>
                </p:panelGrid>
            </f:view>
        </h:form>
    </h:body>

在pom.xml文件中添加以下内容,不要删除Primefaces 4.0依赖项。

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

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.0</version>
    </dependency>

@BehnamSafari 我认为你已经有了,如果你想要的话,我可以提供给你。 - Sheel
我完全困惑了,我删除了那个项目,打开了一个新的项目,却又出现了新的错误! - Behnam Safari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接