Desarrollo web uploadfile struts

0

Por admin | Para la categoría de struts | noticia del 27-04-2010

Ejemplo para subir un archivo zip mediante struts


form bean, se declara el nombre del formulario bean como uploadForm en atributo type se declara la ruta de la clase bean

1
2
3
 <!-- el formbean solamente necesita el name y el type  -->
    <form-bean name="uploadForm" 
    type="formularios.Formularioupload"/>

En el archivo de configuración del struts-config.xml en la seccion de actions mediante el atributo path indicamos que struts responda ante una acción uploadfile con la página ubicada en /pages/formularioloadfile.jsp en cargada de mostrar un formulario para subir el archivo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
         <action path="/uploadfile"
         forward="/pages/formulariouploadfile.jsp">
         </action>
 
         <action                 
         path="/subirarchivo"
         type="acciones.SubirArchivo"
         scope="request"
         name="uploadForm"
         validate="true" 
         input="/pages/formulariouploadfile.jsp">
 
         <forward name="subido" path="/pages/mostrarInformacion.jsp"/>
         </action>

Si se subió el archivo web correctamente se realiza un reenvio a la página mostrarinformación para indicar un mensaje de confirmación al usuario, en caso contrario mediante el atributo input se indica que la propia página jsp de subida del archivo muestre por pantalla el mensaje correspondiente según el error cometido

Código de la clase subir archivo

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
package acciones;
 
import org.apache.struts.action.Action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import formularios.Formularioupload;
import java.io.FileOutputStream;
import java.io.File;
 
 
 
public class SubirArchivo extends Action {
 
	private ActionForward envio;
 
 
	public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{	
		Formularioupload formularioSubido = (Formularioupload) form;
		FileOutputStream fileoutputstream = null;
 
		try
		{
			FormFile fichero = formularioSubido.getFichero();
			String ruta = this.getServlet().getServletContext().getRealPath("/upload/")+fichero.getFileName();
			fileoutputstream = new FileOutputStream(new File(ruta));
			fileoutputstream.write(fichero.getFileData());
 
		}
		finally
		{
		  if(fileoutputstream !=null)
		  {
			  fileoutputstream.close();
		  }
		}
		return mapping.findForward("subido");
	}
 
 
}

Código de la página jsp encargada de mostrar el formulario de subida de archivo

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
<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html:html>
<head>
<html:base/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><bean:message key="uploadfile.titulo"/></title>
<link rel="stylesheet" type="text/css" href="../css/estilo.css" /> 
</head>
<body>
<div id="contenedor">
 
 <h2><bean:message key="uploadfile.titulo"/> </h2>
 
 <div id="errores">
  <html:errors/>
 </div>
 
 <div id="contenido">
 
 <div id="imagen">
 <html:img srcKey="uploadfile.imagen" altKey="uploadfile.imagen.alt"/>
 </div>
 
 <html:form method="post" action="/subirarchivo" enctype="multipart/form-data">
 
 <div id="campo">
 
 <bean:message key="uploadfile.fichero"/>  
 
 
 <html:file  property="fichero"/>
 
 <br/>
 
 <html:submit styleClass="boton" value="enviar"/>
 
 </div>
 
 </html:form>
 </div>
 <div id="pie">
 <p> www.railsymas.com </p> 
 </div>
 
 </div>
 </body>
</html:html>

En el fichero de propiedades

1
2
3
4
5
6
7
8
9
#uploadfile
uploadfile.titulo = formulario uploadfile
uploadfile.fichero = introduce el fichero a subir
uploadfile.imagen = ../imagenes/subirarchivo.png
uploadfile.imagen.alt = imagen archivo 
error.fichero.vacio = el fichero esta vac&iacute;o 
error.fichero.tipo =  el archivo no es de tipo zip
error.fichero.tamanio = error el tamaño excede lo permitido
uploadfile.resultado = formulario subido

clase bean para el formulario

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package formularios;
 
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionErrors;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
 
public class Formularioupload extends ActionForm {
 
	static final long serialVersionUID = 1L;
 
	private FormFile fichero;
	private String informacion;
 
	public String getInformacion() {
		return informacion;
	}
 
	public void setInformacion(String informacion) {
		this.informacion = informacion;
	}
 
	public FormFile getFichero() {
		return fichero;
	}
 
	public void setFichero(FormFile fichero) {
		this.fichero = fichero;
	}
 
 
	public ActionErrors  validate (ActionMapping mapping, HttpServletRequest request)
	{
 
		ActionErrors errores = new ActionErrors ();
 
		//ya esta subido miramos si es del tipo indicado
		if (fichero.getFileSize() == 0)
		{
			//esta vacío
			errores.add("fichero", new ActionMessage ("error.fichero.vacio"));
		}		
		else
		{
 
		  if ( !fichero.getContentType().equals("application/x-zip-compressed"))
		  {
			  errores.add("fichero",new ActionMessage("error.fichero.tipo"));
 
			  System.out.print(fichero.getContentType());
		  }
 
		  else
		  {  
			if ( fichero.getFileSize() > 2000000 ) 
			{
				errores.add("fichero", new ActionMessage("error.fichero.tamanio"));
			}
 
		  }
 
		}
 
		return errores;
	}
 
 
}

Situación en la que hemos dado al botón de enviar sin haber seleccionado un archivo

Error de formato de archivo

Situación el archivo, sí tiene el formato zip pero nos hemos excedido de tamaño soportado por la aplicación

Situación en la que hemos enviado correctamente el archivo

Para comprobar el fichero subido al proyecto desplegamos la aplicación en el servidor tomcat mediante un war del proyecto

Comentarios cerrados automáticamente al pasar más de un año