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.

One comment

  • Hana

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

    Reply

Leave a Reply

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