This Post shows how to implement a Java web application that uploads files to server and save the files into folders and save it's path into database.
Steps you need to follow
1. Create a Mysql database table.
2. Create a upload form page.
3. Create a folder in your 'C' drive named images;
4. Create a File upload Servlet.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
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("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50)
public class FileUploadServlet extends HttpServlet {
private static final String SAVE_DIR="images";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String savePath = "C:" + File.separator + SAVE_DIR;
File fileSaveDir=new File(savePath);
if(!fileSaveDir.exists()){
fileSaveDir.mkdir();
}
In this servlet, we use two annotations:
@WebServlet: marks this servlet so that the servlet container will load it at startup, and map it to the URL pattern /FileUploadServlet.
@MultipartConfig: indicates this servlet will handle multipart request. We restrict maximum size of the upload file up to 16 MB.
Now your file is successfully uploaded in your folder and the path is stored in mysql.
Go in c drive and check it out and check for entry in mysql fire a query(select * from customerDetail) on mysql.
Steps you need to follow
1. Create a Mysql database table.
2. Create a upload form page.
3. Create a folder in your 'C' drive named images;
4. Create a File upload Servlet.
Query for create a database table :
create database UploadFile;
use UploadFile;
CREATE TABLE customerDetail(
'contact_id' int(11) not null auto_increment,
'first_name' varchar(50) not null,
'last_name' varchar(50) not null,
'file' varchar(200) not null,
primary key(contact_id)
);
'photo' is varchar type because I am storing path of the file in this field, if you want to insert whole file in mysql database then you need to set type of 'file' to 'blob'. In this example i am not using blob because it may be cause of image distortion or a little bit hard to implement, in blob field firstly we need to covert file into bytes and then store in mysql.
Coding for uploadform.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">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<head>
<title>Image Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
<table width="400px" align="center" border=0>
<tr>
<td align="center" colspan=2>
Image Details</td>
</tr>
<tr>
<td align="center" colspan=2>
Image Details</td>
</tr>
<tr>
<td>First Name </td>
<td>
<input type="text" name="firstname">
</td>
</tr>
<tr>
<td>Last Name </td>
<td>
<input type="text" name="lastname">
</td>
</tr>
<tr>
<td>Image Link: </td>
<td>
<input type="file" name="file">
</td>
</tr>
<tr>
<td></td>
<td>
<td>First Name </td>
<td>
<input type="text" name="firstname">
</td>
</tr>
<tr>
<td>Last Name </td>
<td>
<input type="text" name="lastname">
</td>
</tr>
<tr>
<td>Image Link: </td>
<td>
<input type="file" name="file">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" value="Submit"></td>
</tr>
</tr>
</table>
</form>
</body>
</html>
</form>
</body>
</html>
You need to set enctype of form tag to "multipart/form-data" it tells that form contain multipart data.
This page contain two text fields for first name and last name and one file type field for files, after submitting the form data send to FileUploadServlet servlet where all other processing is to be done.
This page contain two text fields for first name and last name and one file type field for files, after submitting the form data send to FileUploadServlet servlet where all other processing is to be done.
Coding for FileUploadServlet.java:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
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("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50)
public class FileUploadServlet extends HttpServlet {
private static final String SAVE_DIR="images";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String savePath = "C:" + File.separator + SAVE_DIR;
File fileSaveDir=new File(savePath);
if(!fileSaveDir.exists()){
fileSaveDir.mkdir();
}
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
Part part=request.getPart("file");
String fileName=extractFileName(part);
/*if you may have more than one files with same name then you can calculate some random characters and append that characters in fileName so that it will make your each image name identical.*/
part.write(savePath + File.separator + fileName);
/*
String lastName=request.getParameter("lastname");
Part part=request.getPart("file");
String fileName=extractFileName(part);
/*if you may have more than one files with same name then you can calculate some random characters and append that characters in fileName so that it will make your each image name identical.*/
part.write(savePath + File.separator + fileName);
/*
//You need this loop if you submitted more than one file
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}*/
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/UploadFile","root","root");
String query="INSERT INTO customerDetail (first_name, last_name, file) values (?, ?, ?)";
PreparedStatement pst;
pst=con.prepareStatement(query);
pst.setString(1, firstName);
pst.setString(2,lastName);
String filePath= savePath + File.separator + fileName ;
pst.setString(3,filePath);
pst.executeUpdate();
}
// file name of the upload file is included in content-disposition header like this:
//form-data; name="dataFile"; filename="PHOTO.JPG"
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}*/
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/UploadFile","root","root");
String query="INSERT INTO customerDetail (first_name, last_name, file) values (?, ?, ?)";
PreparedStatement pst;
pst=con.prepareStatement(query);
pst.setString(1, firstName);
pst.setString(2,lastName);
String filePath= savePath + File.separator + fileName ;
pst.setString(3,filePath);
pst.executeUpdate();
}
// file name of the upload file is included in content-disposition header like this:
//form-data; name="dataFile"; filename="PHOTO.JPG"
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}
@WebServlet: marks this servlet so that the servlet container will load it at startup, and map it to the URL pattern /FileUploadServlet.
@MultipartConfig: indicates this servlet will handle multipart request. We restrict maximum size of the upload file up to 16 MB.
Now your file is successfully uploaded in your folder and the path is stored in mysql.
Go in c drive and check it out and check for entry in mysql fire a query(select * from customerDetail) on mysql.