Primefaces FileUpload组件示例教程

时间:2020-02-23 14:41:38  来源:igfitidea点击:

今天,我们将研究Primefaces FileUpload组件。
HTML为您提供了文件输入标签来选择文件,但是我们需要做更多的工作才能将文件上传到服务器。
Primefaces为您提供了现成的FileUpload组件,从而减轻了您的负担,该组件可帮助您创建漂亮的UI,并具有后端支持,可将文件上传到服务器。

Primefaces FileUpload

我们将研究可在应用程序中使用的Primefaces FileUpload组件功能。

本教程假定您具有Primeface的基本知识,否则请阅读Primefaces示例。

Primefaces FileUpload基本信息

TagfileUpload
Component Classorg.primefaces.component.fileupload.FileUpload
Component Typeorg.primefaces.component.FileUpload
Component Familyorg.primefaces.component
Renderer Typeorg.primefaces.component.FileUploadRenderer
Renderer Classorg.primefaces.component.fileupload.FileUploadRenderer

Primefaces FileUpload属性

NameDefaultTypeDescription
idnullStringUnique identifier of the component.
renderedtruebooleanBoolean value to specify the rendering of the component, when set to false component will not be rendered
bindingnullObjectAn el expression that maps to a server side UIComponent instance in a backing bean
valuenullObjectValue of the component than can be either an EL expression of a literal text
converternullConverter/StringAn 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.
immediatefalseBooleanWhen set true, process validations logic is executed at apply request values phase for this component
requiredfalseBooleanMarks component as required.
validatornullMethodExprA method expression that refers to a method validating the input
valueChangeListenernullMethodExprA method expression that refers to a method for handling a valueChangeEvent
requiredMessagenullStringMessage to be displayed when required field validation fails
converterMessagenullStringMessage to be displayed when conversion fails.
validatorMessagenullStringMessage to be displayed when validation fails.
widgetVarnullStringName of the client side widget.
updatenullStringComponent(s) to update after fileupload completes.
processnullStringComponent(s) to process in fileupload request.
fileUploadListenernullMethodExprMethod to invoke when a file is uploaded.
multiplefalseBooleanAllows choosing of multi file uploads from native
autofalseBooleanWhen set to true, selecting a file starts the upload process implicitly
labelChooseStringLabel of the browse button.
allowTypesnullStringRegular expression for accepted file types,
sizeLimitnullIntegerIndividual file size limit in bytes.
fileLimitnullIntegerMaximum number of files allowed to upload.
stylenullStringInline style of the component.
styleClassnullStringStyle class of the component.
modeadvancedStringMode of the fileupload, can be simple or advanced.
uploadLabelUploadStringLabel of the upload button.
cancelLabelCancelStringLabel of the cancel button.
invalidSizeMessagenullStringMessage to display when size limit exceeds.
invalidFileMessagenullStringMessage to display when file is not accepted.
fileLimitMessagenullStringMessage to display when file limit exceeds.
dragDropSupporttrueBooleanSpecifies dragdrop based file selection from filesystem, default is true and works only on supported browsers
onstartnullStringClient side callback to execute when upload begins.
onerrornullStringCallback to execute if fileupload request fails.
oncompletenullStringClient side callback to execute when upload ends.
disabledfalseBooleanDisables component when set true.
messageTemplate{name} {size}StringMessage template to use when displaying file validation errors
previewWidth80IntegerWidth 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>
  • 自动:这是默认模式,如果选择了JSF运行时至少为2.2本机上载器,则Primefaces会通过检查运行时环境来尝试检测最佳方法。

  • 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名称应与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>theitroad 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.theitroad.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.theitroad</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引擎是自动的。

  • 与UploadedFile实例相关联的fileUpload组件的value属性。

  • 使用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>theitroad 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.theitroad.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,因为它们没有更改。

  • FileUpload组件的值属性与UploadedFile实例相关联,因为FileUploadListener也会侦听该组件。

  • FileUploadListener接收FileUploadEvent作为参数。

  • 单击上传操作后,将执行FileUploadListener并创建并传递FileUploadEvent。

演示的结果将是带有两个其他按钮的上传组件的新视图;一个用于上传,另一个用于取消。

重要的是,请注意以下几点:

  • 上载的文件在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>theitroad 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.theitroad.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>theitroad 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文件上传部分页面更新

在fileUpload过程完成后,您可以使用Primefaces PPR(部分页面渲染)来更新页面上的任何组件。
FileUpload为此配备了update属性。
以下示例在文件上传后使用growl组件显示"文件成功上传"消息。
咕messages声组件将在后面讨论消息时进行讨论。

文件上载后,以下代码片段可帮助您显示消息。

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>theitroad 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.theitroad.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组件定义了更新属性,这将导致通过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>theitroad 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>theitroad 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>theitroad 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="theitroad: Invalid Size"
								invalidFileMessage="theitroad: Invalid File Type"
								fileLimitMessage="theitroad: 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代码,则我们对该文件不做任何事情。
但是在现实生活中,我们可以使用UploadedFilegetInputstream()方法获取文件数据并将其另存为服务器或者数据库中的文件。