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.

 

UploadImage.java

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

 

result.jsp

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

 

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.

 

viewImage.jsp

It contains an image tag to display the image.

 

getImage.jsp

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

 

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 comments

  • Hana

    Hi this has been really helpful! I was wondering how do I upload several images at once? 🙂

    Reply
  • shibo

    it is really awesome

    Reply
  • Neha

    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

    Reply
    • ayesha

      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

      Reply
  • Amal

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

    Reply
  • Amal

    I puted the same code , db …. not working 🙁 plz i need your helps !!!

    Reply
  • fixa

    sir, can you show the process from upload,edit until delete??

    Reply
  • ram

    Field ‘id’ doesn’t have a default value i have an error sir

    Reply
    • vishal

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

      Reply
  • vishal

    Solved my problem…
    Thanks admin 🙂

    Reply
  • Ashit Panda

    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 !!!

    Reply
  • Ajay Gautam

    Thanks Buddy

    Reply
  • Jack R

    thanks for this code…

    Reply
  • Joy

    Thanks

    Reply
  • Adrian Mills

    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.

    Reply
    • Adrian Mills

      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.

      Reply
  • Adrian Mills

    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.

    Reply
  • hema

    sir, what should be the type of image of bean class so that it would be compatible with inputstream

    Reply
  • adil

    explain this line code

    byte byteArray[] = blob.getBytes(1, (int)blob.length());

    Reply
  • harika

    hi,I would like to display details of a person along wwith his photo,how can i do this?

    Reply
  • manasa

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

    Reply
  • Blaga

    Thx man

    Reply
  • RITIK

    Thanks man.. Most helpful..

    Reply
  • Tulasi

    sir please check this code I got exception /*null pointer Exception*/

    Reply
  • deepthi

    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)

    Reply
  • Aye

    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

    Reply
  • nandhu

    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

    Reply

Leave a Reply

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