Este es el cdigo para poder subir ficheros al servidor y registrarlos en la base de
datos. Se necesita aadir al proyecto las siguientes libreras: 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 cdigo modularizado. Por ejemplo, en este ejemplo existe una clase Imagen que contiene todos las funciones y mtodos que manipulen las imgenes. En este cdigo aparece el formulario para subir imagen al servidor, y una vez subida, aparecer el formulario para darle nombre y descripcin:
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 pgina. <a href="index.jsp">Inicia sesin</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 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 pericin DiskFileItemFactory factory = new DiskFileItemFactory();
// tamao por encima del cual los ficheros son escritos directamente en disco factory.setSizeThreshold(4096); // directorio en el que se escribirn los ficheros con tamao 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);
} /** * @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();