Primefaces的文件上传组件示例教程
今天我们将介绍Primefaces的FileUpload组件。HTML提供了文件输入标签来选择文件,但要将文件上传到服务器,我们需要更多的操作。Primefaces通过提供现成的FileUpload组件,减轻了这个负担,帮助您创建美观的UI,并为文件上传提供后台支持。
Primefaces文件上传
我们将了解Primefaces FileUpload组件的功能,您可以在您的应用程序中使用。这个教程假设您具有Primeface的基本知识,如果没有,请先看Primefaces示例。
Primefaces 文件上传基本信息
Tag | fileUpload |
---|---|
Component Class | org.primefaces.component.fileupload.FileUpload |
Component Type | org.primefaces.component.FileUpload |
Component Family | org.primefaces.component |
Renderer Type | org.primefaces.component.FileUploadRenderer |
Renderer Class | org.primefaces.component.fileupload.FileUploadRenderer |
Primefaces文件上传属性
Name | Default | Type | Description |
---|---|---|---|
id | null | String | Unique identifier of the component. |
rendered | true | boolean | Boolean value to specify the rendering of the component, when set to false component will not be rendered |
binding | null | Object | An el expression that maps to a server side UIComponent instance in a backing bean |
value | null | Object | Value of the component than can be either an EL expression of a literal text |
converter | null | Converter/String | An el expression or a literal text that defines a converter for the component. When it’s an EL expression, it’s resolved to a converter instance. In case it’s a static text, it must refer to a converter id. |
immediate | false | Boolean | When set true, process validations logic is executed at apply request values phase for this component |
required | false | Boolean | Marks component as required. |
validator | null | MethodExpr | A method expression that refers to a method validating the input |
valueChangeListener | null | MethodExpr | A method expression that refers to a method for handling a valueChangeEvent |
requiredMessage | null | String | Message to be displayed when required field validation fails |
converterMessage | null | String | Message to be displayed when conversion fails. |
validatorMessage | null | String | Message to be displayed when validation fails. |
widgetVar | null | String | Name of the client side widget. |
update | null | String | Component(s) to update after fileupload completes. |
process | null | String | Component(s) to process in fileupload request. |
fileUploadListener | null | MethodExpr | Method to invoke when a file is uploaded. |
multiple | false | Boolean | Allows choosing of multi file uploads from native |
auto | false | Boolean | When set to true, selecting a file starts the upload process implicitly |
label | Choose | String | Label of the browse button. |
allowTypes | null | String | Regular expression for accepted file types, |
sizeLimit | null | Integer | Individual file size limit in bytes. |
fileLimit | null | Integer | Maximum number of files allowed to upload. |
style | null | String | Inline style of the component. |
styleClass | null | String | Style class of the component. |
mode | advanced | String | Mode of the fileupload, can be simple or advanced. |
uploadLabel | Upload | String | Label of the upload button. |
cancelLabel | Cancel | String | Label of the cancel button. |
invalidSizeMessage | null | String | Message to display when size limit exceeds. |
invalidFileMessage | null | String | Message to display when file is not accepted. |
fileLimitMessage | null | String | Message to display when file limit exceeds. |
dragDropSupport | true | Boolean | Specifies dragdrop based file selection from filesystem, default is true and works only on supported browsers |
onstart | null | String | Client side callback to execute when upload begins. |
onerror | null | String | Callback to execute if fileupload request fails. |
oncomplete | null | String | Client side callback to execute when upload ends. |
disabled | false | Boolean | Disables component when set true. |
messageTemplate | {name} {size} | String | Message template to use when displaying file validation errors |
previewWidth | 80 | Integer | Width for image previews in pixels. |
“Primefaces文件上传示例” 的一个例子。
要使用FileUpload,您必须通过添加primefaces.UPLOADER的网络部署参数来提供FileUpload引擎,该参数可以接受以下值:web.xml。
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto|native|commons</param-value>
</context-param>
-
- 这是默认模式,Primefaces会通过检查运行环境来尝试检测最佳方法,如果JSF运行时至少为2.2,则选择原生上传方式,否则选择commons。
-
- 原生模式使用servlet 3.x Part API来上传文件,如果JSF运行时小于2.2,则会抛出异常。
- commons选项选择commons fileUpload,需要在部署描述符中进行以下过滤器配置。
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-name 应该与 JSF servlet 的配置名称匹配,也就是 Faces Servlet。或者,你也可以基于 URL-pattern 进行配置。
Primefaces 简单文件上传
简单文件上传模式适用于旧版浏览器,其中文件输入的值应该是一个已上传文件实例。简单上传不支持Ajax上传。请查看下面所需的文件以创建一个简单的文件上传示例。index.xhtml。
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<title>Journaldev Tutorial</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{fileUploadManagedBean.file}" mode="simple"></p:fileUpload>
<p:separator/>
<h:commandButton value="Dummy Action" action="#{fileUploadManagedBean.dummyAction}"></h:commandButton>
</h:form>
</h:body>
</html>
package com.Olivia.prime.faces.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.model.UploadedFile;
@ManagedBean
@SessionScoped
public class FileUploadManagedBean {
UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public String dummyAction(){
System.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());
return "";
}
}
web.xml 网络配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns="https://java.sun.com/xml/ns/javaee" xmlns:web="https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5" metadata-complete="true">
<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>
<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>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
pom.xml -> 项目对象模型文件
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.Olivia</groupId>
<artifactId>Primefaces-FileUpload-Sample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Primefaces-FileUpload-Sample Maven Webapp</name>
<url>https://maven.apache.org</url>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>https://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- Faces Implementation -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<!-- Faces Library -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<!-- Primefaces Version 5 -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0</version>
</dependency>
<!-- JSP Library -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- JSTL Library -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
</project>
简而言之:
-
- 使用的Primefaces FileUpload引擎是自动的。
-
- fileUpload组件的value属性与UploadedFile实例关联。
-
- 使用fileUpload需要在表单中包含fileUpload组件,其enctype为multipart/form-data。
- 提供的虚拟操作用于打印上传文件的名称和大小。
在哪里,demo的结果将是:简单输入按钮已渲染到您的浏览器中。一旦您点击了”虚拟操作”,一个虚拟动作方法将执行,并且上传文件的信息将被打印到您的控制台中,如下所示。
Primefaces 高级文件上传
FileUpload组件提供了简单视图和高级视图。选择高级视图将成为访问上传文件的唯一方式,通过FileUploadListener。一旦文件上传完成并且FileUploadEvent作为参数传递给监听器,监听器将会被处理。请查看下方所需的文件,以帮助您使用高级模式。index.xhtml
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<title>Journaldev Tutorial</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data" style="width:500px">
<p:fileUpload value="#{fileUploadManagedBean.file}" mode="advanced"
fileUploadListener="#{fileUploadManagedBean.fileUploadListener}"></p:fileUpload>
</h:form>
</h:body>
</html>
package com.Olivia.prime.faces.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
@ManagedBean
@SessionScoped
public class FileUploadManagedBean {
UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void fileUploadListener(FileUploadEvent e){
// Get uploaded file from the FileUploadEvent
this.file = e.getFile();
// Print out the information of the file
System.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());
}
}
总结一下:
-
- 因为它们没有发生改变,所以没有提到web.xml和pom.xml。
-
- 文件上传组件的值属性与UploadedFile实例相关联,因为组件还被FileUploadListener监听。
-
- FileUploadListener以FileUploadEvent作为参数接收。
- 一旦点击了“上传”操作,FileUploadListener将被执行,并创建并传递了一个FileUploadEvent。
在demo的结果中,上传组件会显示一个新的视图,包含两个额外的按钮;一个用于上传,另一个用于取消。在执行过程中,请注意以下几点。
-
- 上传的文件通过FileUploadEvent传递,并且可以通过调用事件对象的e.getFile()来访问,该方法返回一个UploadedFile实例。
- 如果您点击“取消”而不是“上传”,上传过程将完全取消。取消上传将阻止监听器被调用。
Primefaces 多文件上传
使用FileUpload组件上传多个文件是可行的,可以从浏览器对话框中选择多个文件。 旧版本的浏览器不支持多次上传。将多个属性设置为true,可以启用多次选择文件,但是多次选择文件并不意味着所有文件将在一个请求中发送到服务器。 但是,它们将逐个发送。请看下面所需的更改,使多次选择生效。index.xhtml
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<title>Journaldev Tutorial</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data" style="width:500px">
<p:fileUpload value="#{fileUploadManagedBean.file}" mode="advanced" multiple="true"
fileUploadListener="#{fileUploadManagedBean.fileUploadListener}"></p:fileUpload>
</h:form>
</h:body>
</html>
package com.Olivia.prime.faces.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
@ManagedBean
@SessionScoped
public class FileUploadManagedBean {
UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void fileUploadListener(FileUploadEvent e){
// Get uploaded file from the FileUploadEvent
this.file = e.getFile();
// Print out the information of the file
System.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());
}
}
在执行应用程序的结果中,需要注意以下几点:
-
- 点击“取消”按钮将取消上传操作并取消所有文件的上传过程。
-
- 点击每个将要上传的文件旁边的X图标,将仅取消相应的文件上传。
- 一旦点击了上传操作,监听器将根据加载的文件数量被调用。
Primefaces自动文件上传
默认行为要求用户触发上传过程,您可以通过将“auto”设置为true来更改这种方式。选择对话框中的文件后,将立即触发自动上传。请看下面所需的更改,使自动上传生效。index.xhtml
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<title>Journaldev Tutorial</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data" style="width:500px">
<p:fileUpload value="#{fileUploadManagedBean.file}" mode="advanced" multiple="true" auto="true"
fileUploadListener="#{fileUploadManagedBean.fileUploadListener}"></p:fileUpload>
</h:form>
</h:body>
</html>
一旦您点击了“打开”按钮,应用程序的执行结果如下所示:上传过程立即开始。
Primefaces 文件上传局部页面更新
文件上传过程完成后,您可以使用Primefaces PPR(局部页面渲染)来更新页面上的任何组件。FileUpload的update属性就是为此目的而设计的。下面的例子展示了在文件上传后使用growl组件显示“文件上传成功”的消息。待进入messages部分时,我们将讨论growl组件。下面的代码片段将帮助您在文件上传后显示一条消息。index.xhtml
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<title>Journaldev Tutorial</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data" style="width:500px">
<p:growl id="msg"></p:growl>
<p:fileUpload value="#{fileUploadManagedBean.file}" mode="advanced"
fileUploadListener="#{fileUploadManagedBean.fileUploadListener}" update="msg"></p:fileUpload>
</h:form>
</h:body>
</html>
package com.Olivia.prime.faces.beans;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
@ManagedBean
@SessionScoped
public class FileUploadManagedBean {
UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void fileUploadListener(FileUploadEvent e){
// Get uploaded file from the FileUploadEvent
this.file = e.getFile();
// Print out the information of the file
System.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());
// Add message
FacesContext.getCurrentInstance().addMessage(null,new FacesMessage("File Uploaded Successfully"));
}
}
在执行的结果中,情况如下:已经将一条消息添加到FacesContext中,并且FileUpload组件定义了 update 属性,将通过Ajax机制渲染该消息。关于Ajax行为将在另一篇教程中讨论。
文件上传过滤器
用户可以被限制只选择您配置的文件类型,下面的示例演示了只接受图像文件(index.xhtml)。
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<title>Journaldev Tutorial</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data" style="width:500px">
<p:growl id="msg"></p:growl>
<p:fileUpload value="#{fileUploadManagedBean.file}" mode="advanced" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
fileUploadListener="#{fileUploadManagedBean.fileUploadListener}" update="msg"></p:fileUpload>
</h:form>
</h:body>
</html>
执行的结果如下:
Primefaces 文件上传大小限制与文件限制
有时候,你需要限制上传文件的大小或上传的文件数量。在Primefaces的FileUpload组件中,实现这些限制并不是什么大问题。你可以通过在FileUpload本身上分别提供sizeLimit和fileLimit属性来实现这些限制。以下是保持用户受限的代码片段:index.xhtml
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<title>Journaldev Tutorial</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data" style="width:500px">
<p:growl id="msg"></p:growl>
<p:fileUpload value="#{fileUploadManagedBean.file}" mode="advanced" multiple="true" fileLimit="3" sizeLimit="2048"
fileUploadListener="#{fileUploadManagedBean.fileUploadListener}" update="msg"></p:fileUpload>
</h:form>
</h:body>
</html>
当你尝试上传超过三个文件或文件大小超过限制时,会显示以下错误消息:
Primefaces文件上传验证消息
提供了invalidFileMessage、invalidSizeMessage和fileLimitMessage选项,以向用户显示验证消息。您可以根据需要为这些验证提供任意消息。请查看下面提供的示例,index.xhtml。
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<title>Journaldev Tutorial</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data" style="width:500px">
<p:growl id="msg"></p:growl>
<p:fileUpload value="#{fileUploadManagedBean.file}"
invalidSizeMessage="JournalDev: Invalid Size"
invalidFileMessage="JournalDev: Invalid File Type"
fileLimitMessage="JournalDev: Invalid File Limit"
mode="advanced" multiple="true" fileLimit="3" sizeLimit="2048"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
fileUploadListener="#{fileUploadManagedBean.fileUploadListener}"
update="msg"></p:fileUpload>
</h:form>
</h:body>
</html>
而且消息应该如下所示:如果您注意到消息已经更改,并且它们提供了不同的文本值。如果您注意到受管bean代码,我们没有对文件做任何操作。然而,在实际生活中的情况下,我们可以使用UploadedFile getInputstream()方法获取文件数据并将其保存为服务器或数据库上的文件。
Primefaces文件上传总结
本教程旨在为您提供有关使用FileUpload Primefaces组件的全面详细说明。FileUpload组件配备了许多功能,可以让您专注于业务而不是尝试实现类似的东西。您可以从下面的链接下载示例项目,并使用其他fileUpload属性来了解更多信息。
下载PrimeFaces文件上传项目。