Hi, Friends Here the sample code for upload a File or Image using java(Servlets). Apache Tomcat server is one of the most famous server for execute servlets. In this example I am using Apache Tomcat server.
The hierarchy structure to deploy the servlet file in tomcat web server
In our example "Web application name" is "upload"
Note : Create one extra folder that is "UserUploadFiles" , Here we can save our uploaded files.
In order to compile and run this Java web application in any web server e.g. Tomcat, you need to include following dependency JAR in WEB-INF lib folder.
commons-fileupload-1.2.2.jar
(https://mega.co.nz/#!rc9GRDIA!Pfl4gQY_sUw26MLrfQPKhb4dkS7S--A0x36NiQ-cGJ4).
commons-io-2.4.jar (https://mega.co.nz/#!6E9hyRTB!RZQCJw4V3Ms6U7FTZWJkhIpJIMrlKEDe03mUX8Cn5K8).
You can download Apache Commons IO jar and Apache Commons FileUpload jar from URLs.
1. index.html which contains HTML content to setup a form, which allows user to select and upload file to server.
2. UploadFile Servlet which handles file upload request and uses Apache FileUpload library to parse multipart form data
3. web.xml to configure servlet in Java web application.
Save this file in "upload" folder......
Save File Name as index.html .
<html>
<head>
<title>File Upload Using Java(Servlet)</title>
</head>
<body>
</br>
</br>
<table border = "1">
<form action="./fileupload" method="post" enctype="multipart/form-data" name="form1" id="form1">
<tr>
<td><b>Upload File or Image</b></td>
<td><input name="file" type="file" id="file"></td>
</tr>
<tr>
<td><center><input type="submit" name="Submit" value="Submit"/></center></td>
<td><input type="reset" name="Reset" value="Reset"/></td>
</tr>
</form>
</table>
</body>
</html>
Save this file in "upload/WEB-INF" folder......
Save File Name as web.xml .
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>UploadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
</web-app>
Save this file in "upload/WEB-INF/classes" folder......
Save File Name as UploadFile.java .
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
public class UploadFile extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String itemName="";
boolean fileUpload=false;
try
{
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
String name = item.getFieldName();
if(name.equals("file"))
{
itemName = item.getName();
//In this example i am usnig ApacheTomcat Server..
//In ApacheTomcat Server our projets were placed in "webapps"..
//Here My Project name is "upload"..
//Create the folder with name "UserUploadFiles"..
//Here you can give the path i.e., where you want to save the File or Image..
String path="./webapps/upload/UserUploadFiles/";
File savedFile = new File(path+"/"+itemName);
out.println("savedFile:"+savedFile);
item.write(savedFile);
fileUpload = true; // If File or Image was sucessfully upload "fileUpload" is "true"
//Otherwise it will "false"
}
}
if(fileUpload==true)
{
out.println("File Uploaded Sucessfully Check in Your Path :)");
}
else
{
out.println("File Uploaded UnSucessfully :(");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
That's all...................
Download FileUploadServlet Example Project.....
(https://mega.co.nz/#!nN8wmKRD!cjpVYa4dnGRrEUQjRp8Gh4Dnzxp2EjskuT2tA3EKbG4)
The hierarchy structure to deploy the servlet file in tomcat web server
In our example "Web application name" is "upload"
Note : Create one extra folder that is "UserUploadFiles" , Here we can save our uploaded files.
In order to compile and run this Java web application in any web server e.g. Tomcat, you need to include following dependency JAR in WEB-INF lib folder.
commons-fileupload-1.2.2.jar
(https://mega.co.nz/#!rc9GRDIA!Pfl4gQY_sUw26MLrfQPKhb4dkS7S--A0x36NiQ-cGJ4).
commons-io-2.4.jar (https://mega.co.nz/#!6E9hyRTB!RZQCJw4V3Ms6U7FTZWJkhIpJIMrlKEDe03mUX8Cn5K8).
You can download Apache Commons IO jar and Apache Commons FileUpload jar from URLs.
1. index.html which contains HTML content to setup a form, which allows user to select and upload file to server.
2. UploadFile Servlet which handles file upload request and uses Apache FileUpload library to parse multipart form data
3. web.xml to configure servlet in Java web application.
Save this file in "upload" folder......
Save File Name as index.html .
<html>
<head>
<title>File Upload Using Java(Servlet)</title>
</head>
<body>
</br>
</br>
<table border = "1">
<form action="./fileupload" method="post" enctype="multipart/form-data" name="form1" id="form1">
<tr>
<td><b>Upload File or Image</b></td>
<td><input name="file" type="file" id="file"></td>
</tr>
<tr>
<td><center><input type="submit" name="Submit" value="Submit"/></center></td>
<td><input type="reset" name="Reset" value="Reset"/></td>
</tr>
</form>
</table>
</body>
</html>
Save this file in "upload/WEB-INF" folder......
Save File Name as web.xml .
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>UploadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
</web-app>
Save this file in "upload/WEB-INF/classes" folder......
Save File Name as UploadFile.java .
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
public class UploadFile extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String itemName="";
boolean fileUpload=false;
try
{
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
String name = item.getFieldName();
if(name.equals("file"))
{
itemName = item.getName();
//In this example i am usnig ApacheTomcat Server..
//In ApacheTomcat Server our projets were placed in "webapps"..
//Here My Project name is "upload"..
//Create the folder with name "UserUploadFiles"..
//Here you can give the path i.e., where you want to save the File or Image..
String path="./webapps/upload/UserUploadFiles/";
File savedFile = new File(path+"/"+itemName);
out.println("savedFile:"+savedFile);
item.write(savedFile);
fileUpload = true; // If File or Image was sucessfully upload "fileUpload" is "true"
//Otherwise it will "false"
}
}
if(fileUpload==true)
{
out.println("File Uploaded Sucessfully Check in Your Path :)");
}
else
{
out.println("File Uploaded UnSucessfully :(");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
That's all...................
(https://mega.co.nz/#!nN8wmKRD!cjpVYa4dnGRrEUQjRp8Gh4Dnzxp2EjskuT2tA3EKbG4)
EmoticonEmoticon