Несколько месяцев назад я написал совет « Как загрузить с PrimeFaces под Tomcat 6 », который использовал версию PrimeFaces 2.2. С тех пор PrimeFaces был изменен, и в текущей версии 3.2 появилось много новых замечательных функций. В этом совете мы рассмотрим все эти функции.
Для начала вам понадобятся следующие JAR-файлы в папке / lib (вы можете взять их отдельно от Интернета или взять этот полный пример с http://www.filefactory.com/file/3lnbxg0x85d/n/primeFileUpload). рар, то они уже включены)
— primefaces-3.2.jar (это то, что я использовал, но вы можете взять последнюю версию библиотеки Prime Faces с сайта PrimeFaces — http://www.primefaces.org ).
— jsf-api-2.0.2-FCS.jar (опять же, возьмите последнюю версию, если считаете, что она вам нужна)
— jsf-impl-2.0.2-FCS.jar
— el-api-2.2.jar
— el- impl-2.2.jar
— commons-io-1.4.jar
— commons-fileupload-1.2.jar
Далее я настроил дескриптор приложения web.xml (в зависимости от версии Prime Faces эти конфигурации могут немного отличаться). В этом дескрипторе я настроил фильтр загрузки Prime Faces и тему PrimeFaces ui-lightness-1.0.4:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<context-param>
<description>Context param for JSTL 1.2 to work in Tomcat 6 sun RI
</description>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<context-param>
<description>Parameter required by Mojarra 2.0</description>
<param-name>com.sun.faces.allowTextChildren</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
<param-value>true</param-value>
</context-param>
<!-- Adding a PrimeFaces theme -->
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>ui-lightness</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>10240</param-value> <!-- 10 Mb -->
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Затем я написал простую страницу JSF для тестирования компонента загрузки Prime Faces:
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Prime Faces</title>
<style type="text/css">
.ui-fileupload {
width: 800px;
margin: 0 auto;
}
</style>
</h:head>
<h:body>
<h:outputText value="PrimeFaces Single Upload"
style="font:30px bold; margin-left:15%;"/>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
label="Choose a file"
sizeLimit="1048576"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="The maximum file size allowed is 1 Megabyte !"
invalidFileMessage="You are allowed to upload only images !"
/>
<p:growl id="messages" showDetail="true" sticky="true"/>
</h:form>
<h:outputText value="PrimeFaces Multiple Upload"
style="font:30px bold; margin-left:15%;"/>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
label="Choose a file"
sizeLimit="10485760"
multiple="true"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="The maximum file size allowed is 10 Megabytes !"
invalidFileMessage="You are allowed to upload only images !"
/>
<p:growl id="messages" showDetail="true" life="5000"/>
</h:form>
<h:outputText value="PrimeFaces Auto Upload"
style="font:30px bold; margin-left:15%;"/>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
label="Choose a file"
auto="true"
sizeLimit="10485760"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="The maximum file size allowed is 10 Megabytes !"
invalidFileMessage="You are allowed to upload only images !"
/>
<p:growl id="messages" showDetail="true" life="5000"/>
</h:form>
<h:outputText value="PrimeFaces Drag and Drop Upload"
style="font:30px bold; margin-left:15%;"/>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
label="Choose a file or drag and drop it here"
sizeLimit="10485760"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="The maximum file size allowed is 10 Megabytes !"
invalidFileMessage="You are allowed to upload only images !"
/>
<p:growl id="messages" showDetail="true" life="5000"/>
</h:form>
</h:body>
</html>
Как видите, p: fileUpload очень гибкий и настраиваемый, что позволяет нам задавать характеристики загрузки с помощью нескольких простых атрибутов. В дальнейшем нам нужен управляемый компонент, способный справиться с самой загрузкой. Возможная реализация (вероятно, не самая лучшая, но точно не самая плохая) приведена ниже:
package com.extensions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.event.FileUploadEvent;
@ManagedBean(name = "fileUploadController")
@RequestScoped
public class uploadFilesBean {
//Primitives
private static final int BUFFER_SIZE = 6124;
private String folderToUpload;
/** Creates a new instance of UploadBean */
public uploadFilesBean() {
}
public void handleFileUpload(FileUploadEvent event) {
ExternalContext extContext =
FacesContext.getCurrentInstance().getExternalContext();
File result = new File(extContext.getRealPath
("//WEB-INF//files//" + event.getFile().getFileName()));
System.out.println(extContext.getRealPath
("//WEB-INF//files//" + event.getFile().getFileName()));
try {
FileOutputStream fileOutputStream = new FileOutputStream(result);
byte[] buffer = new byte[BUFFER_SIZE];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
FacesMessage msg =
new FacesMessage("File Description", "file name: " +
event.getFile().getFileName() + "<br/>file size: " +
event.getFile().getSize() / 1024 +
" Kb<br/>content type: " +
event.getFile().getContentType() +
"<br/><br/>The file was uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not uploaded!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
}
Загруженные файлы отправляются в папку / WEB-INF / files.
Вот хороший скриншот загрузки Prime Faces:
Вот и все! Надеюсь, вам понравится!
Загрузите полный пример, протестированный под Tomcat 6, здесь