Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

Create an application for upload (save) file in hard disk
Previous Home Next

In this servlet program, any file can be upload/save into destination folder or server.Two important jar (easily found on http://www.apache.org ) must be added into library folder of program. These jar provide very important classes for performing upload/ save file action on server/ hard drive.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
 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_3_0.xsd">
 <servlet>
  <servlet-name>uploadFileServlet</servlet-name>
  <servlet-class>r4r.servlet.uploadFileServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>uploadFileServlet</servlet-name>
  <url-pattern>/uploadFileServlet</url-pattern>
 </servlet-mapping>
 <session-config>
  <session-timeout>
    30
  </session-timeout>
  </session-config>
</web-app>

 

Index.jsp

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
 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_3_0.xsd">
 <servlet>
  <servlet-name>uploadFileServlet</servlet-name>
  <servlet-class>r4r.servlet.uploadFileServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>uploadFileServlet</servlet-name>
  <url-pattern>/uploadFileServlet</url-pattern>
 </servlet-mapping>
 <session-config>
  <session-timeout>
    30
  </session-timeout>
  </session-config>
</web-app>

Servlet Program

/*
 * Save as a uploadFileServlet.java
 */
package r4r.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author R4R
 */
public class uploadFileServlet extends HttpServlet {

private static final String FILE_PATH = "c:/Temp";

protected void processRequest(HttpServletRequest request,
 HttpServletResponse response)throws ServletException,IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here */
out.println("<html>");
out.println("<head>");
out.println("<title>" + getServletInfo() + "</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet uploadFileServlet at "
          + request.getContextPath() + "</h1>");
out.println("<form name=\"form\" action=\"uploadFileServlet\
  " method=\"POST\" enctype=\"multipart/form-data\">");
out.println(" Select File: <input type=\
      "file\" name=\"myFile\" value=\"\" size=\"30\" />");
out.println("<BR><input type=\"submit\" value=\"Processing Image\" />");
out.println("<input type=\"reset\" value=\" Reset \" />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}

@Override
protected void doGet(HttpServletRequest request,
 HttpServletResponse response)throws ServletException,IOException
{
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request,
 HttpServletResponse response)throws ServletException,IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Check that we have a file upload request
boolean isMultipart = 
	ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload fileUpload = 
	new ServletFileUpload(factory);
fileUpload.setSizeMax(-1);  // set max size
try {
// Parse the request
List items = fileUpload.parseRequest(request);
// Iterate upcoming request
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
// Store every request into FileItem 
FileItem fileItem = (FileItem) iterator.next();
if (!fileItem.isFormField()) {
// Get File name with file extension
String prefix =
	FilenameUtils.getBaseName(fileItem.getName());
String suffix =
	FilenameUtils.getExtension(fileItem.getName());
// Create a file into given destination
File file = File.createTempFile(prefix
	 + "_", "." + suffix, new File(FILE_PATH));
// writing data to a File
OutputStream os = new FileOutputStream(file);
// Copy bytes from an InputStream to an OutputStream.
IOUtils.copy(fileItem.getInputStream(), os);
String filename = file.getName();
out.println("File '" + "<b>" + filename 
	+ "</b>" + "' successfully write in hardDisk on Path : " 
+ "<b>" + FILE_PATH + "</b><BR>");
// Close all resource
file.deleteOnExit();
os.close();
} else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
out.println(HttpServletResponse.SC_BAD_REQUEST);
}
}
} catch (FileUploadException ex) {
Logger.getLogger(uploadFileServlet.
	class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
}

@Override
public String getServletInfo() {
return "r4r.co.in-uploadFileServlet";
}
}
Output of Program
Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: