📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Tools and technologies used
- JSP - 2.2 +
- IDE - STS/Eclipse Neon.3
- JDK - 1.8 or later
- Apache Tomcat - 8.5
- Servlet API - 2.5
- MySQL - mysql-connector-java-8.0.13.jar
Development Steps
- Create an Eclipse Dynamic Web Project
- Add Dependencies
- Project Structure
- MySQL Database Setup
- Create a FileUploadDao.java
- Create a FileUploadServlet.java
- Creating a User Profile form - upload-file.jsp
- Create a JSP Page for Success Message - message.jsp
- Deploying and Testing the Application Demo
1. Create an Eclipse Dynamic Web Project
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version.
2. Add Jar Files to Classpath
- jsp-api.2.3.1.jar
- servlet-api.2.3.jar
- mysql-connector-java-8.0.13.jar
- jstl-1.2.jar
3. Project Structure
4. MySQL Database Setup
CREATE DATABASE 'java_demo';
USE demo;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`photo` mediumblob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
5. Create a FileUploadDao.java
package net.javaguides.fileupload.dao;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class FileUploadDao {
private static final String url = "jdbc:mysql://localhost:3306/java_demo?useSSL=false";
private static final String user = "root";
private static final String password = "root";
private static final String sql = "INSERT INTO users (first_name, last_name, photo) values (?, ?, ?)";
public int uploadFile(String firstName, String lastName, InputStream file) {
int row = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try (Connection connection = DriverManager
.getConnection(url, user, password);
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection
.prepareStatement(sql)) {
preparedStatement.setString(1, firstName);
preparedStatement.setString(2, lastName);
if (file != null) {
// fetches input stream of the upload file for the blob column
preparedStatement.setBlob(3, file);
}
// sends the statement to the database server
row = preparedStatement.executeUpdate();
} catch (SQLException e) {
// process sql exception
printSQLException(e);
}
return row;
}
private void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
if (file != null) {
// fetches input stream of the upload file for the blob column
preparedStatement.setBlob(3, file);
}
6. Create a FileUploadServlet.java
package net.javaguides.fileupload.controller;
import java.io.IOException;
import java.io.InputStream;
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 net.javaguides.fileupload.dao.FileUploadDao;
@WebServlet("/uploadServlet")
@MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1 L;
private FileUploadDao fileUploadDao;
@Override
public void init() {
fileUploadDao = new FileUploadDao();
}
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
String message = null;
// 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();
}
// sends the statement to the database server
int row = fileUploadDao.uploadFile(firstName, lastName, inputStream);
if (row > 0) {
message = "File uploaded and saved into database";
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/message.jsp")
.forward(request, response);
}
}
- @WebServlet: marks this servlet so that the servlet container will load it at startup, and map it to the URL pattern /uploadServlet.
- @MultipartConfig: indicates this servlet will handle the multipart request. We restrict the maximum size of the upload file up to 16 MB.
Part filePart = request.getPart("photo");
inputStream = filePart.getInputStream();
7. Creating a User Profile form - upload-file.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>File Upload Servlet JSP JDBC MySQL Example</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>
<body>
<div class="container col-lg-6">
<h1 class="text-center">File Upload to Database Example - Servlet JSP JDBC MySQL </h1>
<div class="card">
<div class="card-body">
<form method="post" class="form-group" action="uploadServlet"
enctype="multipart/form-data">
<div class="form-group">
<label for="first name">First Name: </label> <input type="text"
class="form-control" name="firstName" size="50" />
</div>
<div class="form-group">
<label for="last name">Last Name: </label> <input type="text"
class="form-control" name="lastName" size="50" />
</div>
<div class="form-group">
<label for="Profile Photo">Profile Photo:</label> <input
type="file" name="photo" size="50" />
</div>
<input type="submit" value="Save" class="btn btn-success">
</form>
</div>
</div>
</div>
</body>
</html>
8. Create a JSP Page for Success Message - 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>Success massage</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>
<body>
<center>
<div class="alert alert-success">
<strong><%=request.getAttribute("Message")%></strong>
</div>
</center>
</body>
</html>
9. Deploying and Testing the Application Demo
10. Test in MySQL Workbench
select * from users;
Related Servlet Posts
- What is a Servlet in Java?
- Servlet Life Cycle
- Servlet Interface Example
- GenericServlet Class Example
- HttpServlet Class Example Tutorial
- HttpServlet doGet() Method Example
- HttpServlet doPost() Method Example
- @WebServlet Annotation Example
- @WebInitParam Annotation Example
- @WebListener Annotation Example
- @WebFilter Annotation Example
- @MultipartConfig Annotation Example
- How to Return a JSON Response from a Java Servlet
- Servlet Registration Form + JDBC + MySQL Database Example
- Login Form Servlet + JDBC + MySQL Example
- Servlet JDBC Eclipse Example Tutorial
- JSP Servlet JDBC MySQL CRUD Example Tutorial
- Servlet + JSP + JDBC + MySQL Example
- Registration Form using JSP + Servlet + JDBC + Mysql Example
- Login Form using JSP + Servlet + JDBC + MySQL Example
- JSP Servlet Hibernate CRUD Example
- JSP Servlet Hibernate Web Application
- Hibernate Registration Form Example with JSP, Servlet, MySQL
- Login Form using JSP + Servlet + Hibernate + MySQL Example
I am unable to upload the file. After clicking on uploading file it is showing null please help me with this issue
ReplyDelete