웹사이트 검색

Primefaces FileUpload 구성 요소 예제 자습서


오늘 우리는 Primefaces FileUpload 구성 요소를 살펴볼 것입니다. HTML은 파일을 선택할 수 있는 파일 입력 태그를 제공하지만 파일을 서버에 업로드하려면 더 많은 것이 필요합니다. Primefaces는 파일을 서버에 업로드하기 위한 백엔드 지원과 함께 아름다운 UI를 만드는 데 도움이 되는 미리 만들어진 FileUpload 구성 요소를 제공하여 이러한 부담을 제거했습니다.

Primefaces 파일업로드

애플리케이션에서 사용할 수 있는 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 웹 배포 매개변수를 추가하여 FileUpload 엔진을 제공해야 합니다. web.xml

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

  1. auto: 이것은 기본 모드이며 Primefaces는 JSF 런타임이 2.2 이상인 경우 기본 업로더가 선택된 경우 런타임 환경을 확인하여 최상의 방법을 감지하려고 합니다. 그렇지 않으면 commons입니다.
  2. 기본: 기본 모드는 servlet 3.x Part API를 사용하여 파일을 업로드하고 JSF 런타임이 2.2 미만인 경우 예외가 발생합니다.
  3. 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은 이 경우 Faces Servlet인 JSF 서블릿의 구성된 이름과 일치해야 합니다. 또는 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>

요약:

  1. 사용되는 Primefaces FileUpload 엔진은 자동입니다.
  2. UploadedFile 인스턴스와 연결된 fileUpload 구성 요소의 값 속성
  3. fileUpload를 사용하려면 양식 내에 fileUpload 구성요소를 포함해야 하며 enctype은 multipart/form-data입니다.
  4. 제공된 더미 액션은 업로드된 파일의 이름과 크기를 출력하는 데 사용됩니다.

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){
		// 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());
	}
}

요약:

  1. web.xml과 pom.xml은 변경되지 않았기 때문에 언급되지 않았습니다.
  2. FileUploadListener가 수신하는 구성 요소로서 UploadedFile 인스턴스와 연결된 FileUpload 구성 요소의 값 속성
  3. FileUploadListener는 FileUploadEvent를 매개변수로 받습니다.
  4. 업로드 작업을 클릭하면 FileUploadListener가 실행되고 FileUploadEvent가 생성되어 전달됩니다.

  1. 업로드된 파일은 FileUploadEvent 내에서 전달되며 UploadedFile 인스턴스를 반환하는 이벤트 개체에 대해 e.getFile()을 호출하여 액세스할 수 있습니다.
  2. 업로드 대신 취소를 클릭하면 업로드 프로세스가 완전히 취소됩니다. 업로드를 취소하면 리스너가 호출되지 않습니다.

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.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 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());
	}
}

  1. 취소 버튼을 사용하여 업로드를 취소하면 모든 파일의 업로드 프로세스가 취소됩니다.
  2. 업로드할 모든 파일 옆에 있는 아이콘 X를 클릭하면 업로드된 해당 파일만 취소됩니다.
  3. 업로드 작업을 클릭하면 로드된 파일 수만큼 리스너가 호출됩니다.

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 파일 업로드 부분 페이지 업데이트

fileUpload 프로세스가 완료되면 Primefaces PPR(부분 페이지 렌더링)을 사용하여 페이지의 구성 요소를 업데이트할 수 있습니다. FileUpload는 이를 위해 업데이트 속성을 갖추고 있습니다. 다음 예는 파일 업로드 후 으르렁거리는 구성 요소를 사용하여 "파일 업로드 성공\ 메시지를 표시합니다. 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){
		// 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"));
	}
}

파일 업로드 필터

사용자는 구성한 파일 형식만 선택하도록 제한할 수 있습니다. 아래 예는 이미지만 허용하는 방법을 보여줍니다. <코드>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>

Primefaces FileUpload 요약

이 튜토리얼은 FileUpload Primefaces 구성요소 사용에 대한 자세한 설명을 제공하기 위한 것입니다. 비슷한 것을 구현하려고 시도하는 대신 비즈니스에 집중할 수 있는 많은 기능을 갖춘 FileUpload 구성 요소입니다. 아래 링크에서 샘플 프로젝트를 다운로드하고 다른 fileUpload 속성을 사용하여 자세히 알아볼 수 있습니다.

PrimeFaces 파일 다운로드프로젝트 업로드