Saturday, 17 March 2018

Upload File In Mysql Database using JSP and Servlet




Requirements

1. Servlet APT 3.x.x
 Otherwise through exceptions for getPart Method


2. Mysql Connector-5.1.x
Otherwise through exception for setBlob Method instead we use setBinaryStream


Create Three Files and Table in the Database

1. Upload.jsp
2.FileUploadDBServlet.java (servlet File)
3.Message.jsp

1.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo
</head>
<body>
    <center>
        <h1>File Upload to Database Demo

        <form method="post" action="FileUploadDBServlet" enctype="multipart/form-data">
            <table border="0">
                <tr>
                    <td>Photo: </td>
                    <td><input type="file" name="photo" size="50"/></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Save">
                    </td>
                </tr>
            </table>
        </form>
    </center>
</body></html>


2. FileUploadDBServlet

//package net.codejava.upload;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.servlet.*;
    @WebServlet("/uploadServlet")
@MultipartConfig(maxFileSize = 16177215)    // upload file's size up to 16MB

public class FileUploadDBServlet extends HttpServlet
{

        // database connection settings
        private String dbURL = "jdbc:mysql://localhost:3306/imageupload";
        private String dbUser = "root";
        private String dbPass = "rsb";

        protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
        {
//            // gets values of text fields
//            String firstName = request.getParameter("firstName");
//            String lastName = request.getParameter("lastName");

            InputStream inputStream = null; // input stream of the upload file

            // obtains the upload file part in this multipart request
            Part filePart = request.getPart("photo");
            if (filePart != null) {
                // prints out some information for debugging
                System.out.println(filePart.getName());
                System.out.println(filePart.getSize());
                System.out.println(filePart.getContentType());

                // obtains input stream of the upload file
                inputStream = filePart.getInputStream();
            }

            Connection conn = null; // connection to the database
            String message = null;  // message will be sent back to client

            try {
                // connects to the database
//                //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//                Class.forName("com.mysql.jdbc.Driver");
//                conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
                  try{
                Class.forName("com.mysql.jdbc.Driver");
                }catch(Exception e){System.out.println(e);}
                        conn=DriverManager.getConnection("jdbc:mysql://localhost/imageupload","root","rsb");

                // constructs SQL statement
                String sql = "INSERT INTO imageup (imagep) values (?)";
                PreparedStatement statement = conn.prepareStatement(sql);
                //statement.setString(1, firstName);
                //statement.setString(2, lastName);

                if (inputStream != null) {
                    // fetches input stream of the upload file for the blob column
                    statement.setBinaryStream(1, (InputStream)inputStream,100000);
                }

                // sends the statement to the database server
                int row = statement.executeUpdate();
                if (row > 0) {
                    message = "File uploaded and saved into database";
                }
            } catch (SQLException ex) {
                message = "ERROR: " + ex.getMessage();
                ex.printStackTrace();
            } finally {
                if (conn != null) {
                    // closes the database connection
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
                // sets the message in request scope
                request.setAttribute("Message", message);

                // forwards to the message page
                getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
            }
        }
    }


3. Message.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
    <center>
        <h3><%=request.getAttribute("Message")%></h3>
    </center>
</body>
</html>




Table

create table imageup(image longblog);




3 comments:

Note: only a member of this blog may post a comment.