primefaces教程

Today we will look into the Primefaces FileUpload component. HTML provides you file input tag to select the file, but we need a lot more to upload a file to the server. Primefaces has removed that burden by providing you a ready-made FileUpload component that help you in creating beautiful UI with backend support for upload files to the server.

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

Primefaces FileUpload (Primefaces FileUpload)

We will look into the Primefaces FileUpload component features that you can use in your application.

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

This tutorial assumes that you have basic knowledge of Primeface, if not please go through Primefaces Example.

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

Primefaces FileUpload基本信息 (Primefaces FileUpload Basic Info)

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
标签 上传文件
组件类别 org.primefaces.component.fileupload.FileUpload
组件类型 org.primefaces.component.FileUpload
组件族 org.primefaces.component
渲染器类型 org.primefaces.component.FileUploadRenderer
渲染器类 org.primefaces.component.fileupload.FileUploadRenderer

Primefaces FileUpload属性 (Primefaces FileUpload Attributes)

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.
名称 默认 类型 描述
ID 空值 组件的唯一标识符。
呈现 真正 布尔值 布尔值,用于指定组件的呈现,当设置为false时将不呈现组件
捆绑 空值 目的 El表达式,它映射到支持Bean中的服务器端UIComponent实例
空值 目的 组件的值不能是文字文本的EL表达式
转换器 空值 转换器/字符串 El表达式或文字文本,定义了组件的转换器。 当是EL表达式时,它将解析为转换器实例。 如果是静态文本,则必须引用转换器ID。
即时 布尔型 设置为true时,将在此组件的应用请求值阶段执行流程验证逻辑
需要 布尔型 根据需要标记组件。
验证器 空值 方法专家 引用验证输入的方法的方法表达式
valueChangeListener 空值 方法专家 引用用于处理valueChangeEvent的方法的方法表达式
requiredMessage 空值 必填字段验证失败时显示的消息
converterMessage 空值 转换失败时显示的消息。
验证器消息 空值 验证失败时显示的消息。
widgetVar 空值 客户端小部件的名称。
更新 空值 文件上传完成后要更新的组件。
处理 空值 在文件上传请求中要处理的组件。
fileUploadListener 空值 方法专家 上传文件时调用的方法。
布尔型 允许从本地选择多文件上传
汽车 布尔型 设置为true时,选择文件将隐式启动上传过程
标签 选择 浏览按钮的标签。
allowTypes 空值 接受文件类型的正则表达式,
sizeLimit 空值 整数 单个文件的大小限制(以字节为单位)。
fileLimit 空值 整数 允许上传的最大文件数。
样式 空值 组件的内联样式。
styleClass 空值 组件的样式类。
模式 高级 文件上传的模式可以是简单的也可以是高级的。
uploadLabel 上载 上传按钮的标签。
cancelLabel 取消 取消按钮的标签。
invalidSizeMessage 空值 超过大小限制时显示的消息。
invalidFileMessage 空值 不接受文件时显示的消息。
fileLimitMessage 空值 超出文件限制时显示的消息。
dragDropSupport 真正 布尔型 指定从文件系统中基于拖放的文件选择,默认为true,仅在受支持的浏览器上有效
启动时 空值 上传开始时执行客户端回调。
错误 空值 如果文件上传请求失败,则执行回调。
未完成 空值 上传结束时执行客户端回调。
残障人士 布尔型 设置为true时禁用组件。
messageTemplate {name} {size} 显示文件验证错误时要使用的消息模板
PreviewWidth 80 整数 图像预览的宽度(以像素为单位)。

Primefaces文件上传示例 (Primefaces File Upload Example)

For making use of FileUpload, you have to provide the FileUpload engine by adding primefaces.UPLOADER web deployment paramater that might take the below values:

为了使用FileUpload,您必须通过添加primefaces.UPLOADER Web部署参数来提供FileUpload引擎, 参数可能采用以下值:

web.xml

web.xml

<context-param><param-name>primefaces.UPLOADER</param-name><param-value>auto|native|commons</param-value>
</context-param>
  1. auto: This is the default mode and Primefaces tries to detect the best method by checking the runtime environment, if JSF runtime is at least 2.2 native uploader is selected, otherwise commons.自动 :这是默认模式,如果选择了JSF运行时至少2.2本机上载器,则Primefaces会通过检查运行时环境来尝试检测最佳方法,否则为通用模式。
  2. native: Native mode uses servlet 3.x Part API to upload the files and if JSF runtime is less 2.2 an exception is being thrown.native :纯模式使用Servlet 3.x Part API上载文件,如果JSF运行时小于2.2,则将引发异常。
  3. commons: This option chooses commons fileUpload, it requires the following filter configuration in your deployment descriptor.commons :此选项选择commons fileUpload,它需要在部署描述符中进行以下过滤器配置。

web.xml

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>

Note the servlet-name should match the configured name of the JSF servlet which is Faces Servlet in this case. Alternatively, you can do a configuration based on URL-pattern as well.

注意,该servlet名称应与JSF servlet的配置名称匹配,在这种情况下,该名称是Faces Servlet。 另外,您也可以基于URL模式进行配置。

Primefaces简单文件上传 (Primefaces Simple File Upload)

Simple file upload mode works in legacy browsers, with a file input whose value should be an UploadedFile instance. Ajax uploads are not supported in the simple upload. Look below for these files required for making a simple file upload sample.

简单文件上传模式适用于旧版浏览器,其文件输入的值应为UploadedFile实例。 简单上载不支持Ajax上载。 在下面查找制作简单文件上传示例所需的这些文件。

index.xhtml

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

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/javaeehttps://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

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>

As a summary:

作为总结:

  1. Primefaces FileUpload engine that’s used is auto.使用的Primefaces FileUpload引擎是auto
  2. fileUpload component’s value attribute associated with the UploadedFile instance.与UploadedFile实例关联的fileUpload组件的value属性。
  3. Using of fileUpload requires including the fileUpload component within a form, its enctype is multipart/form-data.使用fileUpload需要在表单中包含fileUpload组件,其enctype为multipart / form-data
  4. Dummy action provided has used to print out the name and size of the uploaded file.提供的虚拟动作已用于打印上载文件的名称和大小。

Where, the result of demo will be: Simple input button has been rendered into your browser.

演示的结果将是:简单的输入按钮已呈现到浏览器中。

And once you’ve clicked on the Dummy Action a dummy action method is executed and the information of uploaded file gets printed into your console like below.

一旦您单击了虚拟动作”,就会执行一个虚拟动作方法,并且上载文件的信息将打印到您的控制台中,如下所示。

Primefaces高级文件上传 (Primefaces Advanced File Upload)

FileUpload component provides you a simple view and an advanced view. Choosing of advanced view makes the only available way for accessing uploaded files is through the FileUploadListener. The listener will be processed as soon as the file is uploaded and a FileUploadEvent has been passed into listener as a parameter.

FileUpload组件为您提供了简单视图和高级视图。 选择高级视图使访问上传文件的唯一可用方法是通过FileUploadListener。 上载文件并将FileUploadEvent作为参数传递到侦听器后,将立即处理该侦听器。

Look below at the required files that help you using advanced mode.

在下面查看有助于您使用高级模式的必需文件。

index.xhtml

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){// Get uploaded file from the FileUploadEventthis.file = e.getFile();// Print out the information of the fileSystem.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());}
}

As a summary:

作为总结:

  1. Neither web.xml nor pom.xml have been mentioned, cause they haven’t changed.没有提及web.xml和pom.xml,因为它们没有更改。
  2. FileUpload component’s value attribute associated with the UploadedFile instance, as the component also listened by the FileUploadListener.FileUpload组件的值属性与UploadedFile实例相关联,因为FileUploadListener也侦听该组件。
  3. FileUploadListener receives a FileUploadEvent as a parameter.FileUploadListener接收FileUploadEvent作为参数。
  4. Once you’ve clicked on the Upload action, the FileUploadListener will be executed and a FileUploadEvent has been created and passed.单击上操作后,将执行FileUploadListener并创建并传递FileUploadEvent。

Where, the result of demo will be a new view of upload component with two additional buttons; one for upload and the latter for cancel.

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

It’s important to notice the following points as a result of execution:

重要的是要注意执行以下几点:

  1. The file uploaded is passed within the FileUploadEvent and it can be accessed by invoking e.getFile() against event object which returns an UploadedFile instance.上传的文件在FileUploadEvent中传递,可以通过对事件对象调用e.getFile()来访问它,该事件对象返回一个UploadedFile实例。
  2. The upload process would be cancelling totally, if you’ve clicked on Cancel instead of Upload. Canceling the upload will prevent the listener from getting invoked.如果您单击取消而不是上传 ,则上传过程将完全被取消。 取消上载将阻止调用侦听器。

Primefaces多个文件上传 (Primefaces Multiple File Uploads)

Uploading multiple files using the FileUpload component is applicable so that multiple files can be selected from browser dialog. Multiple uploads are not supported in legacy browsers. Set multiple attribute to true enabling multiple selections of files, however, multiple selections of files doesn’t mean all files will be sent into the server using one request. However, they will be sent one by one.

使用FileUpload组件上传多个文件是适用的,因此可以从浏览器对话框中选择多个文件。 旧版浏览器不支持多次上传。 将multiple属性设置为true可以启用文件的多个选择,但是,文件的多个选择并不意味着所有文件都将使用一个请求发送到服务器。 但是,它们将被一一发送。

Look below at the required change that makes multiple selections applicable.

下面查看使多个选择适用的必需更改。

index.xhtml

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){// Get uploaded file from the FileUploadEventthis.file = e.getFile();// Print out the information of the fileSystem.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());}
}

Where, the result of executing the application looks like below:

执行应用程序的结果如下所示:

It’s important to notice the following points from the demo:

请注意演示中的以下几点,这一点很重要:

  1. Cancelling the upload using Cancel button, should lead us into canceling the upload process of all files.使用“ 取消”按钮取消上传,应引导我们取消所有文件的上传过程。
  2. Clicking into icon X that’s beside every single file that will be uploading, cause the corresponding file uploaded to be canceled only.单击将要上传的每个文件旁边的图标X,将导致仅取消相应的上传文件。
  3. Once you’ve clicked on Upload action, the listener will be invoked by the number of files that get loaded.单击“上传”操作后,将通过加载的文件数来调用侦听器。

Primefaces自动文件上传 (Primefaces Auto File Upload)

The default behavior requires users to trigger the upload process, you can change this way by setting auto to true. Auto uploads are triggered as soon as files are selected from the dialog.

默认行为要求用户触发上传过程,您可以通过将auto设置为true来更改此方式。 从对话框中选择文件后,就会触发自动上传。

Look below at the required change that makes auto upload applicable.

在下面查看使自动上传适用的必要更改。

index.xhtml

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>

Where, the result of executing the application looks like below:

执行应用程序的结果如下所示:

Once you’ve clicked Open into your browser window, Uploading process has been started instantly.

在浏览器窗口中点击打开后,上传过程即刻开始。

Primefaces文件上传部分页面更新 (Primefaces File Upload Partial Page Update)

After the fileUpload process completes you can use the Primefaces PPR (Partial Page Render) to update any component on the page. FileUpload is equipped with the update attribute for this purpose. Following example displays a “File Uploaded Successfully” message using the growl component after file upload. Growl component will be discussed later when coming into messages.

在完成fileUpload过程之后,您可以使用Primefaces PPR(部分页面渲染)来更新页面上的任何组件。 FileUpload为此配备了update属性。 以下示例在文件上传后使用咆哮组件显示“文件成功上传”消息。 发出消息时将在后面讨论Growl组件。

The following fragment of codes helps you display a message once the file has been uploaded.

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

index.xhtml

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){// Get uploaded file from the FileUploadEventthis.file = e.getFile();// Print out the information of the fileSystem.out.println("Uploaded File Name Is :: "+file.getFileName()+" :: Uploaded File Size :: "+file.getSize());// Add messageFacesContext.getCurrentInstance().addMessage(null,new FacesMessage("File Uploaded Successfully"));}
}

Where, the result of execution looks like below:

执行结果如下所示:

A message has been added into FacesContext and the FileUpload component defines the update attribute which will cause the message to be rendered through Ajax mechanism. Ajax behavior will be discussed later in a separate tutorial.

消息已添加到FacesContext中 ,并且FileUpload组件定义了update属性,该属性将导致消息通过Ajax机制呈现。 稍后将在单独的教程中讨论Ajax行为。

文件上传过滤器 (File Upload Filters)

Users can be restricted to only select the file types you’ve configured, the example below demonstrates how to accept images only.

可以限制用户只选择您配置的文件类型,下面的示例演示了如何仅接受图像。

index.xhtml

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>

And the result of execution looks like below

执行结果如下所示

Primefaces文件上传大小限制和文件限制 (Primefaces File Upload Size Limit & File Limit)

Sometimes, you need to restrict the size of the uploaded file or the number of files to be uploaded. Doing such these restrictions aren’t big issue with Primefaces FileUpload component. You can achieve these restrictions by providing sizeLimit & fileLimit attributes respectively against FileUpload itself.

有时,您需要限制上传文件的大小或要上传的文件数。 进行这些限制对于Primefaces FileUpload组件不是什么大问题。 您可以通过分别针对FileUpload本身提供sizeLimit和fileLimit属性来实现这些限制。

Following the code fragments that keep your users restricted:

遵循限制用户使用的代码片段:

index.xhtml

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>

When you try to upload more than three files or file its size exceeds the limit an error messages will be displayed like below:

当您尝试上传三个以上文件或文件大小超过限制时,将显示如下错误消息:

Primefaces文件上传验证消息 (Primefaces File Upload Validation Message)

invalidFileMessage, invalidSizeMessage and fileLimitMessage options are provided to display validation messages to the users. You can provide whatever you want of messages for those validations. Look below at the provided example.

提供invalidFileMessageinvalidSizeMessagefileLimitMessage选项可向用户显示验证消息。 您可以提供所需的任何消息来进行这些验证。 在下面看提供的示例。

index.xhtml

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>

And the messages should look like below:

并且消息应如下所示:

If you’ve noticed the messages have been changed and they’re provided different text values. If you notice the managed bean code, we are not doing anything with the file. However in real life situations, we can use UploadedFile getInputstream() method to get the file data and save it as file on server or database.

如果您发现消息已更改,并为它们提供了不同的文本值。 如果您注意到托管bean代码,那么我们对该文件不做任何事情。 但是,在现实生活中,我们可以使用UploadedFile getInputstream()方法获取文件数据并将其另存为服务器或数据库上的文件。

Primefaces FileUpload摘要 (Primefaces FileUpload Summary)

This tutorial intended to provide you a full detailed explanation about using of FileUpload Primefaces component. FileUpload component equipped with a lot of features that keep your focus on the business instead of trying to implement something similar. You can download the sample project from below link and use other fileUpload attributes to learn more.

本教程旨在为您提供有关使用FileUpload Primefaces组件的完整详细说明。 FileUpload组件具有许多功能,可让您专注于业务而不是尝试实现类似功能。 您可以从下面的链接下载示例项目,并使用其他fileUpload属性来了解更多信息。

Download PrimeFaces FileUpload Project下载PrimeFaces FileUpload项目

翻译自: https://www.journaldev.com/3229/primefaces-fileupload-component-example-tutorial

primefaces教程

primefaces教程_Primefaces FileUpload组件示例教程相关推荐

  1. primefaces教程_Primefaces BlockUI组件示例教程

    primefaces教程 Primefaces BlockUI is used to block interactivity of JSF components with optional ajax ...

  2. primefaces教程_Primefaces仪表板组件示例教程

    primefaces教程 We've mentioned earlier, Primefaces is one of leading libraries that provide you set of ...

  3. primefaces教程_Primefaces日历组件示例教程

    primefaces教程 In our previous tutorials, we've covered several types of Primefaces components such as ...

  4. Primefaces Spring和Hibernate集成示例教程

    Primefaces Spring和Hibernate集成示例教程 欢迎使用Spring Primefaces和Hibernate Integration示例.框架之间的集成是一项复杂的任务,而且大多 ...

  5. primefaces教程_Primefaces AjaxBehavior和AjaxExceptionHandler组件示例教程

    primefaces教程 Different tutorials were provided here have introduced various Primefaces components an ...

  6. android实例教程_改造Android示例教程

    android实例教程 Welcome to Retrofit Android Example Tutorial. Today we'll use the Retrofit library devel ...

  7. expect脚本教程_Expect脚本SSH示例教程

    expect脚本教程 Expect script is a great linux/unix utility. I have to deal with a lot of unix servers in ...

  8. android实例教程_Android内部存储示例教程

    android实例教程 Today we will look into android internal storage. Android offers a few structured ways t ...

  9. ios8升级ios12教程_iOS Hello World示例教程

    ios8升级ios12教程 In this tutorial we'll develop our first iPhone Application which displays a Hello Wor ...

最新文章

  1. oracle参数文件initorcl位置,ORACLE参数文件
  2. 解决Neither the JAVA_HOME nor the JRE_HOME environment variable is defined问题
  3. 【性能优化】小伙伴问我性能指标监控怎么做,这次我安排上了!!
  4. Alluxio及其典型应用场景
  5. 分享10个实用的超绚CSS3按钮设计
  6. linux shell shift命令 参数移动 简介
  7. 如何规划网站设计方案让用户访问更加舒适?
  8. 【转】oracle存储过程常用技巧
  9. mysql bin.000047_mysql-bin.0000X 日志文件处理
  10. 白硕 | 基于区块链的众包社区激励机制
  11. 阿里云助力浙江大学信息化建设,以实时数据驱动校园智能管理
  12. 这11个JavaScript小技巧,你在大多数教程中是找不到的!
  13. flutter列表无法滚动到底部_在闲鱼实习做Flutter是什么感受?
  14. 1.LeetCode字符编辑距离
  15. 用python把unix格式转换成windows格式
  16. 页面定时跳转的js和php的代码实现和页面定时刷新
  17. python 爬糗事百科
  18. EViews-蒙特卡洛模型代码
  19. 算法工程师修仙之路:机器学习实战(四)
  20. 解决鼠标不能移出视频框,切换网页不能播视频的小窍门

热门文章

  1. [转载] python isinstance()方法的使用
  2. [转载] python查看的统计量_python 描述性统计_Python中的基本统计:描述性统计
  3. java中equals,hashcode和==的区别
  4. Salesforce删除数据时出现Insufficient privileges的可能原因
  5. jquery 固定导航
  6. JavaScript使用button提交表单
  7. linux shell 递归统计代码行数
  8. js Function.call
  9. net user test 123456 /add
  10. Asp.Net IIS 管理类(全)