upload primefaces

Hola a todos, sean bienvenidos a un nuevo artículo de la sección de Java en el cual realizaremos la implementación de un upload en PrimeFaces, nuestra página permitira subir varias imágenes y luego presionar un botón con el cual empezar la subida (upload de imagenes), así mismo cada imagen será renombrada al nombre original de esta seguido de la fecha y la hora del servidor, así que sin más empecemos:

upload primefaces

Upload de Imágenes con PrimeFaces

Primero que todo debemos editar nuestro archivo web.xml y añadir un fltro así:

1
2
3
4
5
6
7
8
9
10
11
    <filter>
</filter><filter -name>PrimeFaces FileUpload Filter</filter>
<filter -class>org.primefaces.webapp.filter.FileUploadFilter</filter>
<init -param>
<param -name/>thresholdSize
<param -value/>51200
</init>
<init -param>
<param -name/>uploadDirectory
<param -value/>C:\tmp
</init>

Ahora vamos a crear nuestra vista, desde la cual haremos el llamado al Managed Bean encargado de realizar la subida de las imágenes, seguido lo declararemos para evitar errores.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
< ?xml version=‘1.0’ encoding=‘UTF-8’?>
< !DOCTYPE html PUBLIC «-//W3C//DTD XHTML 1.0 Transitional//EN» «http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd»>
<html xmlns=«http://www.w3.org/1999/xhtml»
     xmlns:ui=«http://xmlns.jcp.org/jsf/facelets»
     xmlns:p=«http://primefaces.org/ui»
     xmlns:h=«http://xmlns.jcp.org/jsf/html»
     xmlns:f=«http://xmlns.jcp.org/jsf/core»>

<body>
<ui:composition template=«./template.xhtml»>
<ui:define name=«content»>
<h:form>
<p:growl id=«msg»></p:growl>
<p:fileupload fileUploadListener=«#{FileUploadManagedBean.upload}»
                                 allowTypes=«/(\.|\/)(gif|jpe?g|png)$/» sizeLimit=«10000000» update=«msg»></p:fileupload>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>

Aquí el ManagedBean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package bean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;

@ManagedBean(name = «FileUploadManagedBean»)
public class FileUploadManagedBean {

private String destination = «D:\\tmp;

public void upload(FileUploadEvent event) {
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
FacesMessage message = new FacesMessage(«El archivo se ha subido con éxito!«);
FacesContext.getCurrentInstance().addMessage(null, message);
} catch (IOException e) {
e.printStackTrace();
}

}
public void copyFile(String fileName, InputStream in) {
try {
OutputStream out = new FileOutputStream(new File(destination + fileName));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
System.out.println(«El archivo se ha creado con éxito!«);

DateFormat dateFormat = new SimpleDateFormat(«yyyyMMdd HH_mm_ss«);
Date date = new Date();
String ruta1 = destination + fileName;
String ruta2 = destination + dateFormat.format(date)+»
«+fileName;
System.out.println(«
Archivo: «+ruta1+» Renombrado a: «+ruta2);
File archivo=new File(ruta1);
archivo.renameTo(new File(ruta2));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

Como pueden ver el método anterior se encarga de crear el archivo y renombrarlo, con esto tendríamos funcionando nuestro multi-upload tan solo ejecutalo y realiza pruebas, recuerda crear el directorio donde se almacenaran las imágenes.

Hasta pronto!.

2 comentario en “Upload de Imágenes con PrimeFaces Java”
  1. Hola, muy bueno tu ejemplo, podrias hacer un tutorial en donde suba la imagen, la actualice en la pagina y luego la pueda guardar en la base de datos.
    nota. ayudame porfa

  2. muy bueno, pero como lo haces con varios archivos ala vez usando handleFileUpload de primefaces

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

×