Sie sind auf Seite 1von 9

Subir ficheros y registrarlos en la base de datos

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:




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>Descripcin:</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 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 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 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);

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;
}
}

Das könnte Ihnen auch gefallen