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:
[Link]
[Link]
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:
[Link]
<%@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=[Link](false);
if([Link]("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([Link]("subido")!=null){
if([Link]("subido").toString().equals("true")){
%>
<p style="color: green">Fichero subido correctamente.</p>
<%
if([Link]("rutaFichero")!=null){
%>
<form method="post" action="[Link]">
<label>Nombre:</label>
<input type="text" id="txtNombreImagen" name="nombre">
<br>
<label>Ruta:
<%=[Link]("rutaFichero")%></label>
<input type="hidden" id="txtRuta" name="ruta"
value="<%=[Link]("rutaFichero")%>">
<br>
<label>Descripcin:</label>
<input type="text" id="txtDescripcion" name="descripcion">
<input type="hidden" id="txtId" name="id"
value="<%=[Link]("idLogeado").toString()%>">
<input type="submit" id="idEnviar" value="Enviar">
</form>
<%
}
}else{
%>
<p style="color: red">Error al subir fichero.</p>
<%
}
}
if([Link]("errorInsercion")!=null){
if([Link]("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="[Link]">Volver</a>
<%
}else{
%>
No esta logeado para entrar en esta pgina. <a
href="[Link]">Inicia sesin</a>
<%
}
%>
</body>
</html>
[Link]
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ria;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import
[Link];
import
[Link];
import [Link].*;
/**
*
* @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 =
[Link](request);
[Link]("text/html");
PrintWriter out = [Link]();
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
[Link](4096);
// directorio en el que se escribirn los ficheros con
tamao superior al soportado en memoria
[Link](new File(path + "/"));
// nuevo manejador para el fichero
ServletFileUpload upload = new ServletFileUpload(factory);
// maximo numero de bytes
[Link](1024*512);
// ordenamos procesar los ficheros
fileItems = [Link](request);
if (fileItems == null) {
flag=false;
}
// Iteramos por cada fichero
Iterator i = [Link]();
FileItem actual = null;
if ([Link]()) {
actual = (FileItem) [Link]();
fileName= [Link]();
// 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 + [Link]());
// escribimos el fichero colgando del nuevo path
[Link](fichero);
flag = true;
rutaFichero=[Link]();
}
} catch (Exception e) {
[Link]([Link]());
}
/////////////////////////////////////////////////////////////
/////////////////////////
[Link]("rutaFichero",rutaFichero);
[Link]("subido", flag);
[Link]( "/[Link]" ).forward(
request, response );
[Link]();
}
// <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>
}
[Link]
<jsp:useBean id="imagen" class="[Link]"/>
<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=[Link]();
[Link]("errorInsercion", s);
[Link]("subido", "true");
[Link]( "/[Link]" ).forward(
request, response );
%>
</body>
</html>
[Link]
/*
* 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){
[Link]=nombre;
[Link]=ruta;
[Link]=descripcion;
[Link]=votos;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
[Link] = id;
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre the nombre to set
*/
public void setNombre(String nombre) {
[Link] = nombre;
}
/**
* @return the ruta
*/
public String getRuta() {
return ruta;
}
/**
* @param ruta the ruta to set
*/
public void setRuta(String ruta) {
[Link] = ruta;
}
/**
* @return the descripcion
*/
public String getDescripcion() {
return descripcion;
}
/**
* @param descripcion the descripcion to set
*/
public void setDescripcion(String descripcion) {
[Link] = descripcion;
}
/**
* @return the votos
*/
public int getVotos() {
return votos;
}
/**
* @param votos the votos to set
*/
public void setVotos(int votos) {
[Link] = votos;
}
public int subirImagen(){
int s;
MySQL mysql=new MySQL("flickr","//localhost","root",
"forman");
[Link]();
s=[Link]("INSERT INTO imagenes
(nombre,ruta,descripcion,votos,idUsuario) VALUES
('"+getNombre()+"','"+getRuta()+"','"+getDescripcion()+"','0'
,'"+getId()+"');");
[Link]();
return s;
}
}