Below is Code for uploading and downloading file or attachment using java!!!!
upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Example</title>
</head>
<body>
<form id="form1" enctype="multipart/form-data" action="../upload" method="post">
<table>
<tr>
<td> File Name </td>
<td><input type="text" name="filename"/>
</tr>
<tr>
<td>Select File </td>
<td><input type="file" name="file" />
</tr>
<tr><td><input type="submit" value="submit"/></td></tr>
</table>
</form>
</body>
</html>
upload.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class up
*/
public class up extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public up() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
/*
String f1=request.getParameter("file");
f1.
if(f1.endsWith(".txt"))
{
System.out.println(f1);
}
else
{
System.out.println("not a txt file");
}*/
// Apache Commons-Fileupload library classes
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
if (! ServletFileUpload.isMultipartContent(request)) {
System.out.println("sorry. No file uploaded");
return;
}
Connection con=null;
java.util.List items = sfu.parseRequest(request);
FileItem FirstName = (FileItem) items.get(0);
String fn = FirstName.getString();
System.out.println(fn);
FileItem Image = (FileItem) items.get(1);
String type= Image.getContentType();
if(type=="image/jpeg"){
response.setContentType("image/jpeg");
}
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
System.out.println("get connection");
PreparedStatement ps = (PreparedStatement) con.prepareStatement("insert into files_upload(file_name,file_data,file_type) values (?,?,?)");
System.out.println("prepared statement");
ps.setString(1,fn);
ps.setBinaryStream(2, Image.getInputStream(), (int) Image.getSize());
ps.setString(3, type);
ps.executeUpdate();
System.out.println("File Uploaded Successfully.");
}
catch(Exception ex) {
System.out.println(ex);
}
}
}
download.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*,java.util.*,java.sql.*" %>
<!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>view</title>
</head>
<body>
<br><br>
<table width="200px" style="border:1px solid #ff0000;background-color:f7f7f7" align="center">
<tr style="font-weight:bold;">
<td align="center" align="center" colspan=2 style="border-bottom: 2px solid #000000;">Download Files</td>
</tr>
<tr style="font-weight:bold;">
<td align="center" style="border-bottom: 2px solid #000000;">Id</td>
<td align="center" style="border-bottom: 2px solid #000000;">File</td>
</tr>
<%
String connectionURL = "jdbc:mysql://localhost:3306/test";
// String url=request.getParameter("WEB_URL");
// String Content=new String("");
Statement stmt=null;
Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(connectionURL,"root","root");
stmt=con.createStatement();
String qry = "select * from files_upload";
ResultSet rst= stmt.executeQuery(qry);
while(rst.next())
{
%>
<tr>
<td align="center"><%=rst.getInt(1)%></td>
<td align="center">
<a href="../DBFileDownloadServlet?id=<%=rst.getInt(1)%>"><%=rst.getString(2)%></a>
</td>
</tr>
<%
}
}
catch(Exception e){
e.printStackTrace();
}
%>
</table>
</body>
</html>
download.java
import java.io.*;
import java.util.*;
import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class file_download
*/
public class file_download extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public file_download() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int id=0;
if(request.getParameter("id")!=null && request.getParameter("id")!="")
{
id = Integer.parseInt(request.getParameter("id").toString());
}
String connectionURL = "jdbc:mysql://localhost/test";
String url=request.getParameter("WEB_URL");
String Content=new String("");
Statement stmt=null;
Connection con=null;
try
{
String filename="data"+id+".docx";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
stmt=con.createStatement();
String qry = "select * from file where id='"+id+"'";
ResultSet rst= stmt.executeQuery(qry);
if(rst.next())
{
Content=rst.getString("file_data");
}
byte requestBytes[] = Content.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);
response.reset();
response.setContentType("application/*");
response.setHeader("Content-disposition","attachment; filename=" +filename);
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) > 0){
response.getOutputStream().write(buf, 0, len);
}
bis.close();
response.getOutputStream().flush();
}
catch(Exception e){
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}