Save and Retrieve Image from MySQL Database Using Servlet and JSP

Here you will learn how to save and retrieve image from mysql database using servlet and jsp.

This method will work with Servlet 3.0 and MySQL 5.5 and higher versions.

Also Read: How to Connect Java (JDBC) with MySQL or Oracle Database

Save and Retrieve Image from MySQL Database Using Servlet and JSP

Database

Create a table in mysql database with following schema.

Database Name: test

Table Name: data

Save and Retrieve Image from MySQL Database Using Servlet and JSP

Here I have used MEDIUMBLOB datatype to store image in database. It supports maximum 16 MB file. You can also use other types like TINYBLOB (255 bytes), BLOB (64 KB), LONGBLOB (4 GB).

 

Project

Create a dynamic web project with name ImageUploadDownload. The project have following files.

index.jsp

It contains a form to choose image to upload. When user chooses an image and submit form, the request is sent to UploadImage.java.

<html>
    <head>
        <title>Upload Image</title>
    </head>
    
    <body>
    
        <b>Upload | <a href="view.jsp">View</a></b><br/><br/>
        
        <form action="uploadImage" method="post" enctype="multipart/form-data">
            <input type="file" name="image" required="required"/><br/><br/>
            <input type="submit"/>
        </form>
    </body>
</html>

 

UploadImage.java

It is a servlet that is responsible for storing image in database.

package com;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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;

@WebServlet("/uploadImage")
@MultipartConfig(maxFileSize = 16177216)
public class UploadImage extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String connectionURL = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String pass = "root";

		int result = 0;
		Connection con = null;
		Part part = req.getPart("image");

		if(part != null){
			try{
				Class.forName("com.mysql.jdbc.Driver");
			    con = DriverManager.getConnection(connectionURL, user, pass);
			    
			    PreparedStatement ps = con.prepareStatement("insert into data(image) values(?)");
			    InputStream is = part.getInputStream();
			    ps.setBlob(1, is);
			    result = ps.executeUpdate();
			}
			catch(Exception e){
				e.printStackTrace();
			}	
			finally{
				if(con != null){
					try{
						con.close();
					}
					catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}
		
		if(result > 0){
	    	resp.sendRedirect("result.jsp?message=Image+Uploaded");
	    }
		else{
			resp.sendRedirect("result.jsp?message=Some+Error+Occurred");
		}
	}
}

 

result.jsp

This page shows success if image is successfully saved in database otherwise shows error.

<%
String message = request.getParameter("message");
if(message != null){
	out.print(message);
}
%>

 

view.jsp

It contains a form with a text field. User have to enter unique image id and submit the form. The request is sent to viewImage.jsp page.

<html>
    <head>
        <title>View Image</title>
    </head>
    
    <body>
    
        <b>View | <a href="index.jsp">Upload</a></b><br/><br/>
        
        <form action="viewImage.jsp" method="post">
            <input type="text" name="id" required="required" placeholder="enter image id.."/><br/><br/>
            <input type="submit"/>
        </form>
    </body>
</html>

 

viewImage.jsp

It contains an image tag to display the image.

<html>
    <head>
        <title>View Image</title>
    </head>
    
    <body>
    
        <b>View | <a href="index.jsp">Upload</a></b><br/><br/>
        
		<%
		String id = request.getParameter("id");
		%>
		<img src="getImage.jsp?id=<%=id%>" width="400px"/>

    </body>
</html>

 

getImage.jsp

It is responsible for fetching image form database with given image id and display it.

<%@page import="java.sql.Blob"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%
String id = request.getParameter("id");

String connectionURL = "jdbc:mysql://localhost:3306/test";
String user = "root";
String pass = "root";

Connection con = null;

try{
    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection(connectionURL, user, pass);
    
    PreparedStatement ps = con.prepareStatement("select * from data where id=?");
    ps.setString(1, id);
    ResultSet rs = ps.executeQuery();

    if(rs.next()){
        Blob blob = rs.getBlob("image");
        byte byteArray[] = blob.getBytes(1, (int)blob.length());
 
        response.setContentType("image/gif");
        OutputStream os = response.getOutputStream();
        os.write(byteArray);
        os.flush();
        os.close();
    }
}
catch(Exception e){
    e.printStackTrace();
}   
finally{
    if(con != null){
        try{
            con.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
%>

 

Screenshots

Save and Retrieve Image from MySQL Database Using Servlet and JSP Save and Retrieve Image from MySQL Database Using Servlet and JSP

Feel free to ask your queries in comment section.

32 thoughts on “Save and Retrieve Image from MySQL Database Using Servlet and JSP”

        1. Hello sir,

          Kindly sent me java code or any link to refer – insert image to mysql db with controller,bean,dao,service page sir

  1. I want to display all the images in the table column, how can I do that? I don’t want to get photo by id, I want to display all images from a table onto jsp (front).

    Please help me, I’m stuck here for a long time & not getting any solution for this. I want to implement this in my final project please reply asap.

    thanks

    1. your code works for me 🙂 but i want to insert image with the item description price fildes i tried to alter your code but i did get the output but .and i want to display all the image with its details in table format .i don’t want to retrive them using id
      ‘can you please say me the code i need help in my final year project,iam stuck in this particular process for a long time.
      thank you

  2. Hello , plz I need your helps , I want to display image from table column using servlet and jsp (user’s profil picture )

    1. Your id is not taking any value… thats why it is showing that error @ram
      Just make run this command ‘ALTER TABLE MODIFY COLUMN id INT auto_increment;’

  3. It shows an error-
    Method com/mysql/jdbc/PreparedStatement.setBlob(ILjava/io/InputStream;)V is abstract
    com.mysql.jdbc.PreparedStatement.setBlob(PreparedStatement.java)

    If anyone can solve this error !!!

  4. Hello, I really like your code it is awesome looking, I am going to try and run it soon as I am looking for an image
    upload in jsp to mysql database and I really like want you have come up with, however I was wondering do I need a web.xml to go along with this code or not? if So can you please provide the exact web.xml code so i can plug it in my WEB-INF folder, thank you very much. Adrian Mills.

    1. Ok! I got the servlet and all the pages with the web.xml and everything is working properly, however the message that is written in the servlet code for result.jsp is displaying on the page “Some Error Occurred” is coming up, but I know the prgram is working correctly and everything, but I am getting this message on the result.jsp page, can you please help and tell me what the problem is, why i am getting this message, thank you very much. Adrian Mills.

  5. hello, never mind about the error that I was getting from the jsp page , I have figured it out, there was a bug in the mysql.connector.java it was an older connector, and I downloaded the latest version and a later version of mysql and then everything worked perfect thanks again for the code it is awesome, I like this website too, thanks again, bye. Adrian Mills.

  6. Sir, Uploadimage.java is not connecting to index.jsp.
    After uploading image, it is not shwoing uploaded image.

  7. error as follows..please help me

    org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet [com.Upload] in context with path [/USINGJSP] threw exception [Servlet execution threw an exception] with root cause
    java.lang.AbstractMethodError: Method com/mysql/jdbc/ServerPreparedStatement.setBlob(ILjava/io/InputStream;)V is abstract
    at com.mysql.jdbc.ServerPreparedStatement.setBlob(ServerPreparedStatement.java)
    at com.Upload.doPost(Upload.java:45)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

  8. banking project individual form and image for using servlet and jsp how to insert data and image link are connect to database .
    plz tell me

  9. what will do code is executed but error is there

    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server version name: Apache Tomcat/9.0.22
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server built: Jul 4 2019 14:20:06 UTC
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server version number: 9.0.22.0
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: OS Name: Windows 10
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: OS Version: 10.0
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Architecture: amd64
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Java Home: C:\Program Files\Java\jdk1.8.0_211\jre
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: JVM Version: 1.8.0_211-b12
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: JVM Vendor: Oracle Corporation
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: CATALINA_BASE: C:\Users\admin\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: CATALINA_HOME: C:\Program Files\Apache Software Foundation\Tomcat 9.0
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dcatalina.base=C:\Users\admin\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 9.0
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dwtp.deploy=C:\Users\admin\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 9.0\endorsed
    Jul 09, 2020 4:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dfile.encoding=Cp1252
    Jul 09, 2020 4:47:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_211\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.8.0_211/jre/bin/server;C:/Program Files/Java/jdk1.8.0_211/jre/bin;C:/Program Files/Java/jdk1.8.0_211/jre/lib/amd64;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Users\admin\AppData\Local\Programs\Python\Python38-32\Scripts\;C:\Users\admin\AppData\Local\Programs\Python\Python38-32\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;;C:\Users\admin\Desktop;;.]
    Jul 09, 2020 4:47:34 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler [“http-nio-8080”]
    Jul 09, 2020 4:47:36 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler [“ajp-nio-8007”]
    Jul 09, 2020 4:47:36 PM org.apache.catalina.startup.Catalina load
    INFO: Server initialization in [2,729] milliseconds
    Jul 09, 2020 4:47:36 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service [Catalina]
    Jul 09, 2020 4:47:36 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet engine: [Apache Tomcat/9.0.22]
    Jul 09, 2020 4:47:49 PM org.apache.jasper.servlet.TldScanner scanJars
    INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    Jul 09, 2020 4:47:55 PM org.apache.jasper.servlet.TldScanner scanJars
    INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    Jul 09, 2020 4:47:56 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler [“http-nio-8080”]
    Jul 09, 2020 4:47:56 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler [“ajp-nio-8007”]
    Jul 09, 2020 4:47:56 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in [20,741] milliseconds
    Jul 09, 2020 4:49:21 PM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet [jsp] in context with path [/ImageUploadDownload] threw exception [java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:581)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:227)
    at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:115)
    at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:108)
    at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:179)
    at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:120)
    at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
    at org.apache.jsp.getImage_jsp._jspService(getImage_jsp.java:191)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

    plz let me no

Leave a Comment

Your email address will not be published. Required fields are marked *