JSP cargar imagen a Mysql
Publicado por Daniel (12 intervenciones) el 25/06/2019 22:15:51
Hola a todos mi nombre es Daniel, soy nuevo en esto y espero me puedan aportar alguna solución a la aplicación web que manejo.
Bueno tengo una BD en MySql con una tabla llamada "Persona" y tiene los campos: Codigo, Nombre y Foto (tipo de dato MediunBlob); hasta aquí todo bien, luego en la aplicacion web JSP que manejo con MVC (trabajo con Netbeans) tengo los siguientes paquetes:
Paquete Web Pages
- Pagina JSP con nombre "Usuario.jsp"
- Pagina JSP con nombre "Respuesta.jsp"
Paquete Source Packages / Conexion
- Archivo Java con nombre "Conexion.java"
Paquete Source Packages / Modelo
- Archivo Java con nombre "BD_Usuario.java" (Aquí ejecuto las consultas Sql)
- Archivo Java con nombre "Usuario.java" (Aquí creo los constructores, get y set)
Paquete Source Packages / Servlet
- Archivo Servlet con nombre "RegistrarUsuario" (Aquí tengo la petición del usuario)
Bueno no tengo ningún error pero tampoco no me deja inserta ningún valor a la tabla "Persona" de mi BD.
Espero me puedan ayudar un favor, ya que no se exactamente que código me falta o que errores tengo, la verdad nose mucho y recién empiezo con esto de insertar imagen a una BD.
Aquí les comparto el código de mi aplicación y ya de antemano les agradesco mucho.
[img]/usr/tmp/5d12790cabc97-Tabla-persona.PNG[/img]
[img]/usr/tmp/5d12798ddab1f-Estructura-de-la-aplicacion-web.PNG[/img]
Codigo de la pagina JSP "Usuario.jsp"
Codigo de mi clase java "Conexion.java"
Codigo de clase java "Usuario.java"
Codigo de clase java "BD_Usuario.java"
Codigo del Servlet "RegistrarUsuario.java"
Codigo JSP "Respuesta.jsp"
Imagenes de la ejecución
[img]/usr/tmp/5d127d853af01-Ejecucion-de-la-aplicacion-web.PNG[/img]
[img]/usr/tmp/5d127d853bc63-Guardar-datos-a-Mysql.PNG[/img]
[img]/usr/tmp/5d127e09b69a0-Resultado-de-la-ejecucion.PNG[/img]
Bueno tengo una BD en MySql con una tabla llamada "Persona" y tiene los campos: Codigo, Nombre y Foto (tipo de dato MediunBlob); hasta aquí todo bien, luego en la aplicacion web JSP que manejo con MVC (trabajo con Netbeans) tengo los siguientes paquetes:
Paquete Web Pages
- Pagina JSP con nombre "Usuario.jsp"
- Pagina JSP con nombre "Respuesta.jsp"
Paquete Source Packages / Conexion
- Archivo Java con nombre "Conexion.java"
Paquete Source Packages / Modelo
- Archivo Java con nombre "BD_Usuario.java" (Aquí ejecuto las consultas Sql)
- Archivo Java con nombre "Usuario.java" (Aquí creo los constructores, get y set)
Paquete Source Packages / Servlet
- Archivo Servlet con nombre "RegistrarUsuario" (Aquí tengo la petición del usuario)
Bueno no tengo ningún error pero tampoco no me deja inserta ningún valor a la tabla "Persona" de mi BD.
Espero me puedan ayudar un favor, ya que no se exactamente que código me falta o que errores tengo, la verdad nose mucho y recién empiezo con esto de insertar imagen a una BD.
Aquí les comparto el código de mi aplicación y ya de antemano les agradesco mucho.
[img]/usr/tmp/5d12790cabc97-Tabla-persona.PNG[/img]
[img]/usr/tmp/5d12798ddab1f-Estructura-de-la-aplicacion-web.PNG[/img]
Codigo de la pagina JSP "Usuario.jsp"
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
<%@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>
<form action="RegistrarUsuario" method="Post">
<table>
<tr>
<td>
Codigo
</td>
<td>
<input type="text" name="Codigo">
</td>
</tr>
<tr>
<td>
Nombre
</td>
<td>
<input type="text" name="Nombre">
</td>
</tr>
<tr>
<td>
Foto
</td>
<td>
<input type="file" name="Foto">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" value="Enviar">
</td>
</tr>
</table>
</form>
</body>
</html>
Codigo de mi clase java "Conexion.java"
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Conexion {
Connection conectar = null;
public Connection conectar(){
try{
Class.forName("com.mysql.jdbc.Driver");
conectar = DriverManager.getConnection("jdbc:mysql://localhost:3306/prueba","root","");
}catch (ClassNotFoundException | SQLException e){
System.out.println("Error al conectar: "+e.getMessage());
}
return conectar;
}
}
Codigo de clase java "Usuario.java"
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
package Modelo;
public class Usuario {
private int Codigo_Usu;
private String Nombre_Usu;
private String Foto_Usu;
public int getCodigo_Usu() {
return Codigo_Usu;
}
public void setCodigo_Usu(int Codigo_Usu) {
this.Codigo_Usu = Codigo_Usu;
}
public String getNombre_Usu() {
return Nombre_Usu;
}
public void setNombre_Usu(String Nombre_Usu) {
this.Nombre_Usu = Nombre_Usu;
}
public String getFoto_Usu() {
return Foto_Usu;
}
public void setFoto_Usu(String Foto_Usu) {
this.Foto_Usu = Foto_Usu;
}
public Usuario(int Codigo_Usu, String Nombre_Usu, String Foto_Usu) {
this.Codigo_Usu = Codigo_Usu;
this.Nombre_Usu = Nombre_Usu;
this.Foto_Usu = Foto_Usu;
}
public Usuario() {
}
}
Codigo de clase java "BD_Usuario.java"
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
package Modelo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.PreparedStatement;
import java.sql.Connection;
import Conexion.Conexion;
public class BD_Usuario {
public static boolean RegistrarUsuario(Usuario Usu){
boolean resp = false;
File archivoFoto = new File(Usu.getFoto_Usu());
Connection cn;
Conexion con = new Conexion();
cn = con.conectar();
try{
FileInputStream convertir_imagen = new FileInputStream(archivoFoto);
PreparedStatement st = cn.prepareStatement("INERT INTO PERSONA VALUES(?,?,?)");
st.setInt(1, Usu.getCodigo_Usu());
st.setString(2, Usu.getNombre_Usu());
st.setBlob(3, convertir_imagen, archivoFoto.length());
int i = st.executeUpdate();
if(i == 1)
resp = true;
else
resp = false;
st.close();
}catch(FileNotFoundException ex){System.out.println(ex);
}catch(Exception e){System.out.println(e);}
return resp;
}
}
Codigo del Servlet "RegistrarUsuario.java"
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package Servlet;
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 Modelo.Usuario;
import Modelo.BD_Usuario;
@WebServlet(name = "RegistrarUsuario", urlPatterns = {"/RegistrarUsuario"})
public class RegistrarUsuario 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 {
response.setContentType("text/html;charset=UTF-8");
int Codigo = Integer.parseInt(request.getParameter("Codigo"));
String Nombre = request.getParameter("Nombre");
String Foto = request.getParameter("Foto");
if(Nombre.equals("")){
response.sendRedirect("Respuesta.jsp?mens='No deje el campo nombre vacio'");
}else{
Usuario Usu = new Usuario();
Usu.setCodigo_Usu(Codigo);
Usu.setNombre_Usu(Nombre);
Usu.setFoto_Usu(Foto);
boolean resp = BD_Usuario.RegistrarUsuario(Usu);
if(resp){
response.sendRedirect("Respuesta.jsp?mens='Se ha registrado correctamente'");
}else{
response.sendRedirect("Respuesta.jsp?mens='Hubo un problema al registrar'");
}
}
}
// <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>
}
Codigo JSP "Respuesta.jsp"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@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>
<h1 align="center">
<%
if(request.getParameter("mens") != null){
out.println(request.getParameter("mens"));
}
%>
</h1>
<br>
<br>
<p align="center">
<a href="Usuario.jsp">Regresar al inicio</a>
</p>
</body>
</html>
Imagenes de la ejecución
[img]/usr/tmp/5d127d853af01-Ejecucion-de-la-aplicacion-web.PNG[/img]
[img]/usr/tmp/5d127d853bc63-Guardar-datos-a-Mysql.PNG[/img]
[img]/usr/tmp/5d127e09b69a0-Resultado-de-la-ejecucion.PNG[/img]
- InsertarImagen_MysqlJSP.rar(1,0 MB)
Valora esta pregunta


0