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.

10 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
  • 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

Leave a Reply

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