今天我们将研究Primefaces FileUpload组件。HTML提供了file输入标签来选择文件,但我们需要更多的内容才能将文件上传到服务器。Primefaces通过提供一个现成的FileUpload组件来帮助您创建具有后端支持的美观UI,从而解除了这种负担。
Primefaces FileUpload
我们将研究Primefaces FileUpload组件的功能,您可以在应用程序中使用这些功能。本教程假定您具有Primeface的基本知识,如果没有,请查看Primefaces示例。
Primefaces FileUpload基本信息
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 FileUpload属性
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 web部署参数来提供FileUpload引擎,该参数可能采用以下值:web.xml
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto|native|commons</param-value>
</context-param>
- auto:这是默认模式,Primefaces尝试通过检查运行环境来检测最佳方法,如果JSF运行时至少为2.2,则选择本机上传器,否则选择commons。
- native:本机模式使用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模式进行配置。
Primefaces简单文件上传
简单文件上传模式适用于传统浏览器,其中文件输入的值应为 UploadedFile 实例。简单上传不支持 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.journaldev.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.journaldev</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 引擎使用的是auto。
- fileUpload 组件的值属性与 UploadedFile 实例关联。
- 使用 fileUpload 需要将 fileUpload 组件包含在表单中,其 enctype 为multipart/form-data。
- 提供的虚拟操作用于打印上传文件的名称和大小。
在哪里,演示的结果将是:简单输入按钮已经渲染到您的浏览器中。
一旦您点击了虚拟操作,虚拟操作方法将被执行,并且上传文件的信息将被打印到您的控制台中,如下所示。
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.journaldev.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){
// 从FileUploadEvent中获取上传的文件
this.file = e.getFile();
// 打印文件的信息
System.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());
}
}
总结:
- 未提及web.xml和pom.xml,因为它们没有更改。
- FileUpload组件的value属性与UploadedFile实例相关联,因为该组件还受到FileUploadListener的监听。
- FileUploadListener将FileUploadEvent作为参数接收。
- 一旦您点击上传操作,FileUploadListener将被执行,并且FileUploadEvent已创建并传递。
在这里,演示结果将是具有两个额外按钮的上传组件的新视图;一个用于上传,另一个用于取消。重要的是要注意以下执行结果:
- 上传的文件通过FileUploadEvent传递,可以通过调用e.getFile()来访问事件对象,该方法返回一个UploadedFile实例。
- 上传过程将完全取消,如果您点击了取消而不是上传。取消上传将阻止调用侦听器。
Primefaces 多文件上传
使用 FileUpload 组件上传多个文件,以便可以从浏览器对话框中选择多个文件。在旧版浏览器中不支持多个上传。将multiple属性设置为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.journaldev.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){
// 从 FileUploadEvent 获取已上传的文件
this.file = e.getFile();
// 打印文件的信息
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具有此目的的更新属性。以下示例显示了在文件上传后使用growl组件显示“文件成功上传”消息的示例。当涉及到消息时,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.journaldev.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){
// 从FileUploadEvent中获取上传的文件
this.file = e.getFile();
// 打印文件的信息
System.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());
// 添加消息
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文件上传组件限制这些并不是什么大问题。您可以分别针对文件上传本身提供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摘要
这个教程旨在为您提供关于使用FileUpload Primefaces组件的详细全面的解释。FileUpload组件配备了许多功能,可以让您专注于业务,而不是试图实现类似的功能。您可以从下面的链接下载示例项目,并使用其他fileUpload属性来了解更多。
Source:
https://www.digitalocean.com/community/tutorials/primefaces-fileupload-component-example-tutorial