File upload and download program in Java

In this tutorial, we are going to see how to upload and save file into the MySQL database.We are going to implement this using Servlet + Jsp + MySQL.

jars required:


  • commons-fileupload-1.3.jar
  • commons-io-2.4.jar
  • mysql-connector-java-5.1.31.jar

Create Table Query:

CREATE TABLE `file_upload` (
  `image_id` int(11) NOT NULL AUTO_INCREMENT,
  `image_name` varchar(45) DEFAULT NULL,
  `image` mediumblob,
  PRIMARY KEY (`image_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

Code:

Step 1- Create Dynamic Web application in Eclipse.

Step 2- Add above jars in lib folder of the project.



Dao Layer - To interact with database

Note: Update Database credentials in ConnectionDao.java

ConnectionDao.java

package com.javainstance.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author javainstance
 *
 */
public class ConnectionDao {

private static Connection con = null;

public static final String DB_URL = "jdbc:mysql://localhost:3306/uploadfile";
public static final String DB_USERNAME = "root";
public static final String DB_PASSWORD = "Welcome123";

static {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

/**
* @return Connection
*/
public static Connection getConnection() {

return con;

}

public void closeConnection(Connection con) {

if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}



FileDao.java

package com.javainstance.dao;

import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import com.javainstance.model.FileDetail;

/**
 * @author javainstance
 *
 */
public class FileDao {

// To save the file

public int saveFile(String fileName, InputStream inputStream) {
int result = 0;

ConnectionDao dao = new ConnectionDao();
Connection conn = dao.getConnection();

try {
String sql = "INSERT INTO file_upload (image_name,image) values (?,?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, fileName);
statement.setBlob(2, inputStream);
result = statement.executeUpdate();
statement.close();

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return result;

}

/**
* @return list of files
*/
public List<FileDetail> getAllFiles() {

List<FileDetail> list = new ArrayList<>();

try {
ConnectionDao dao = new ConnectionDao();
Connection conn = dao.getConnection();
PreparedStatement ps = conn.prepareStatement("select * from file_upload");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
FileDetail fileDetailt = new FileDetail();
fileDetailt.setFileId(rs.getInt(1));
fileDetailt.setFileName(rs.getString(2));
list.add(fileDetailt);

}
ps.close();

} catch (Exception e) {
e.printStackTrace();
}

return list;
}

/**
* @param fileId
* @return file
*/
public FileDetail downloadFile(int fileId) {

// queries the database
Blob blob = null;
ConnectionDao dao = new ConnectionDao();
Connection conn = dao.getConnection();
FileDetail det = null;
String sql = "SELECT * FROM file_upload WHERE image_id = ?";
PreparedStatement statement;
try {
statement = conn.prepareStatement(sql);
statement.setInt(1, fileId);

ResultSet result = statement.executeQuery();
if (result.next()) {
// gets file name and file blob data
int fId = result.getInt("image_id");
String fileName = result.getString("image_name");
blob = result.getBlob("image");

det = new FileDetail(fId, fileName, blob);

}
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return det;
}
}


Model Layer

FileDetail.java

package com.javainstance.model;

import java.sql.Blob;

/**
 * @author javainstance
 *
 */
public class FileDetail {
private int fileId;
private String fileName;
private Blob fileContent;
public FileDetail() {
super();
}
public FileDetail(int fileId, String fileName, Blob fileContent) {
super();
this.fileId = fileId;
this.fileName = fileName;
this.fileContent = fileContent;
}
public int getFileId() {
return fileId;
}
public void setFileId(int fileId) {
this.fileId = fileId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public Blob getFileContent() {
return fileContent;
}
public void setFileContent(Blob fileContent) {
this.fileContent = fileContent;
}

}

Servlets

FileUploadServlet.java

package com.javainstance.servlet;


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.javainstance.dao.FileDao;
import com.javainstance.model.FileDetail;

/**
 * Servlet implementation class FileUploadServlet
 */

@MultipartConfig(maxFileSize = 16177215)
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* Default constructor.
*/
public FileUploadServlet() {
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileDao dao=new FileDao();
response.setContentType("text/html");  
       PrintWriter out=response.getWriter();   
       out.println("<h1>File List</h1>");  
         
       List<FileDetail> list=dao.getAllFiles();
         
       out.print("<table border='1' width='100%'");  
       out.print("<tr><th>File Id</th><th>File Name</th></tr>");  
       for(FileDetail f:list){  
        out.print("<tr><td>"+f.getFileId()+"</td><td>"+f.getFileName()+"</td><td><a href='/FileOperation/download?id="+f.getFileId()+"'>Download</a></td></tr>");  
       }  
       out.print("</table>");  
         
       out.close();  
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
int result = 0;

InputStream inputStream = null;

Part filePart = request.getPart("image");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}

FileDao fileDao = new FileDao();
if (inputStream != null) {
result = fileDao.saveFile(filePart.getSubmittedFileName(),inputStream);
}

if (result == 1) {
out.println("uploaded...");
} else {

out.println("no file uploaded");
}

}
}

DownloadServlet.java

package com.javainstance.servlet;


import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javainstance.dao.FileDao;
import com.javainstance.model.FileDetail;

/**
 * Servlet implementation class DownloadServlet
 */

public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int BUFFER_SIZE = 4096;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
int id=Integer.parseInt(request.getParameter("id"));
FileDao dao=new FileDao();
FileDetail fileDetail=dao.downloadFile(id);
Blob blob = fileDetail.getFileContent();
         InputStream inputStream;
try {
inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("fileLength = " + fileLength);

        ServletContext context = getServletContext();


       // sets MIME type for the file download
       String mimeType = context.getMimeType(fileDetail.getFileName());
       if (mimeType == null) {        
           mimeType = "application/octet-stream";
       }              
        
       // set content properties and header attributes for the response
       response.setContentType(mimeType);
       response.setContentLength(fileLength);
       String headerKey = "Content-Disposition";
       String headerValue = String.format("attachment; filename=\"%s\"", fileDetail.getFileName());
       response.setHeader(headerKey, headerValue);
       
       // writes the file to the client
       ServletOutputStream outStream = response.getOutputStream();
        
       byte[] buffer = new byte[BUFFER_SIZE];
       int bytesRead = -1;
        
       while ((bytesRead = inputStream.read(buffer)) != -1) {
           outStream.write(buffer, 0, bytesRead);
       }
        
       inputStream.close();
       outStream.close(); 
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        
          
        

               
   } 
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}


JSP Pages

index.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>Insert title here</title>
</head>
<body>
<h1>Upload and Download</h1>
<hr>
<a href="/FileOperation/UploadForm.jsp">Upload File</a>
<a href="/FileOperation/upload">Download Files</a>

</body>
</html>






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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="/FileOperation/upload" method="post"
enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit"/>
</form>

</body>
</html>



web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>UploadImage</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>fileupload</servlet-name>
    <servlet-class>com.javainstance.servlet.FileUploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>fileupload</servlet-name>
    <url-pattern>/upload</url-pattern>
  </servlet-mapping>
<servlet>
    <servlet-name>filedownload</servlet-name>
    <servlet-class>com.javainstance.servlet.DownloadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>filedownload</servlet-name>
    <url-pattern>/download</url-pattern>
  </servlet-mapping>
</web-app>

upload and download file using java



Give you suggestion in comments.If you like the post Share with your friends on social network.


You may be interested in:  Send Mail in Spring MVC using Gmail SMTP.







File upload and download program in Java File upload and download program in Java Reviewed by JavaInstance on 11:27:00 AM Rating: 5

No comments:

Powered by Blogger.