miércoles, 8 de febrero de 2012

Subir ficheros y registrarlos en la base de datos


Este es el código para poder subir ficheros al servidor y registrarlos en la base de datos. Se necesita añadir al proyecto las siguientes librerías:
http://commons.apache.org/fileupload/
http://commons.apache.org/io/
Tener en cuenta que a partir de la entrada anterior, todos los ejemplos aparecerá con el código modularizado. Por ejemplo, en este ejemplo existe una clase Imagen que contiene todos las funciones y métodos que manipulen las imágenes. En este código aparece el formulario para subir imagen al servidor, y una vez subida, aparecerá el formulario para darle nombre y descripción:


subirImagen.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Subir imagen</title>
 </head>
 <body>
 <%
 HttpSession sesion=request.getSession(false);
 if(sesion.getAttribute("idLogeado")!=null){

 %>
 <h1>Subir imagen</h1>
 <form method="post" enctype='multipart/form-data' action="subirImagenServlet">
 Por favor, seleccione fichero a subir<br/>
 <input type="file" name="fichero" /> 
 <input type="submit" />
 </form>
 <%
 if(request.getAttribute("subido")!=null){
 if(request.getAttribute("subido").toString().equals("true")){
 %>
 <p style="color: green">Fichero subido correctamente.</p>
 <%
 if(request.getAttribute("rutaFichero")!=null){
 %>
 <form method="post" action="subirDatosImagenBeans.jsp">
 <label>Nombre:</label>
 <input type="text" id="txtNombreImagen" name="nombre">
 <br>
 <label>Ruta: <%=request.getAttribute("rutaFichero")%></label>
 <input type="hidden" id="txtRuta" name="ruta" value="<%=request.getAttribute("rutaFichero")%>">
 <br>
 <label>Descripción:</label>
 <input type="text" id="txtDescripcion" name="descripcion">
 <input type="hidden" id="txtId" name="id" value="<%=sesion.getAttribute("idLogeado").toString()%>">

 <input type="submit" id="idEnviar" value="Enviar">
 </form>
 <%
 }
 }else{
 %>
 <p style="color: red">Error al subir fichero.</p>
 <%
 }
 }
 if(request.getAttribute("errorInsercion")!=null){
 if(request.getAttribute("errorInsercion").toString().equals("1")){
 %>
 <p style="color: green">Imagen insertada correctamente.</p>
 <%
 }else{
 %>
 <p style="color: red">Error al insertar imagen en la base de datos.</p>
 <%
 }
 }
 %>
 <a href="index.jsp">Volver</a>
 <%
 }else{
 %>
 No esta logeado para entrar en esta página. <a href="index.jsp">Inicia sesión</a>
 <%
 }
 %>

 </body>
</html>

subirImagenServlet.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ria;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.util.*;
/**
 *
 * @author Tarde
 */
@WebServlet(name = "subirImagenServlet", urlPatterns = {"/subirImagenServlet"})
public class subirImagenServlet extends HttpServlet {
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 // si se quiere comprobar que es un request de ficheros
 //boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 boolean flag = false;
 String fileName = "";
 List fileItems = null;
 String path = getServletContext().getRealPath("/")+"imagenes/";
 String rutaFichero="";

 try {
 // construimos el objeto que es capaz de parsear la perición
 DiskFileItemFactory factory = new DiskFileItemFactory(); 

 // tamaño por encima del cual los ficheros son escritos directamente en disco
 factory.setSizeThreshold(4096);
 // directorio en el que se escribirán los ficheros con tamaño superior al soportado en memoria
 factory.setRepository(new File(path + "/"));

 // nuevo manejador para el fichero
 ServletFileUpload upload = new ServletFileUpload(factory);
 // maximo numero de bytes
 upload.setSizeMax(1024*512);
 // ordenamos procesar los ficheros
 fileItems = upload.parseRequest(request);
 if (fileItems == null) {
 flag=false;
 }
 // Iteramos por cada fichero
 Iterator i = fileItems.iterator();
 FileItem actual = null;

 if (i.hasNext()) {

 actual = (FileItem) i.next();
 fileName= actual.getName(); 

 // construimos un objeto file para recuperar el trayecto completo
 File fichero = new File(fileName);
 // nos quedamos solo con el nombre y descartamos el path
 fichero = new File(path + fichero.getName());
 // escribimos el fichero colgando del nuevo path
 actual.write(fichero);

 flag = true;
 rutaFichero=fichero.getName();
 }
 } catch (Exception e) {
 out.println(e.getMessage());
 }

 //////////////////////////////////////////////////////////////////////////////////////

 request.setAttribute("rutaFichero",rutaFichero);
 request.setAttribute("subido", flag);
 request.getRequestDispatcher( "/subirImagen.jsp" ).forward( request, response );

 out.close();
 }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
 /**
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 processRequest(request, response);
 }
/**
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 processRequest(request, response);
 }
/**
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
 @Override
 public String getServletInfo() {
 return "Short description";
 }// </editor-fold>
}
subirDatosImagenBeans.jsp
<jsp:useBean id="imagen" class="ria.Imagen"/>
<jsp:setProperty name="imagen" property="*" />
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>JSP Page</title>
 </head>
 <body>
 <%
 int s=imagen.subirImagen();
 request.setAttribute("errorInsercion", s);
 request.setAttribute("subido", "true");
 request.getRequestDispatcher( "/subirImagen.jsp" ).forward( request, response );
 %>
 </body>
</html>
Imagen.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ria;
/**
 *
 * @author Tarde
 */
public class Imagen {
 //ATRIBUTOS
 private int id;
 private String nombre;
 private String ruta;
 private String descripcion;
 private int votos;

 public Imagen(){

 }
 public Imagen(String nombre,String ruta,String descripcion,int votos){
 this.nombre=nombre;
 this.ruta=ruta;
 this.descripcion=descripcion;
 this.votos=votos;

 }
/**
 * @return the id
 */
 public int getId() {
 return id;
 }
/**
 * @param id the id to set
 */
 public void setId(int id) {
 this.id = id;
 }
/**
 * @return the nombre
 */
 public String getNombre() {
 return nombre;
 }
/**
 * @param nombre the nombre to set
 */
 public void setNombre(String nombre) {
 this.nombre = nombre;
 }
/**
 * @return the ruta
 */
 public String getRuta() {
 return ruta;
 }
/**
 * @param ruta the ruta to set
 */
 public void setRuta(String ruta) {
 this.ruta = ruta;
 }
/**
 * @return the descripcion
 */
 public String getDescripcion() {
 return descripcion;
 }
/**
 * @param descripcion the descripcion to set
 */
 public void setDescripcion(String descripcion) {
 this.descripcion = descripcion;
 }
/**
 * @return the votos
 */
 public int getVotos() {
 return votos;
 }
/**
 * @param votos the votos to set
 */
 public void setVotos(int votos) {
 this.votos = votos;
 }

 public int subirImagen(){
 int s;
 MySQL mysql=new MySQL("flickr","//localhost","root", "forman");
 mysql.inicializarBD();
 s=mysql.insertar("INSERT INTO imagenes (nombre,ruta,descripcion,votos,idUsuario) VALUES ('"+getNombre()+"','"+getRuta()+"','"+getDescripcion()+"','0','"+getId()+"');");
 mysql.cerrarBD();

 return s;
 }
}

7 comentarios:

  1. Se ve bastante buena la aplicacion.. pero tengo una duda e-e... en el formulario


    action="subirImagenServlet"


    en la parte de action.. lo envias directamente a un .java? no surge problemas con eso?

    ResponderEliminar
    Respuestas
    1. Pues no tengo el código en mi IDE para compilarlo y probarlo, pero yo no veo ningún problema, ¿a ti te da error?

      Eliminar
  2. Excelente aporte, funciona de maravilla, ten un buen día.

    ResponderEliminar
    Respuestas
    1. como te funciono no logro que corra, me marca error en MySQL mysql=new MySQL("flickr","//localhost","root", "forman"); y al ahora de presionar enviar me dice que encuentra el subirImagenServlet

      Eliminar
  3. Este comentario ha sido eliminado por el autor.

    ResponderEliminar
  4. Estoy probando el código y me toma el path en /build/web/...

    Esto no sería un probelma si se nos ocurre hacer un Clean and Build del proyecto, perderíamos todos los ficheros...

    Saludos! gracias!

    ResponderEliminar
    Respuestas
    1. No logro que funcione me marca error que no encuentra el subirImagenServlet

      Eliminar