Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for upload (save) multiple file in hard disk
Previous Home Next

In this servlet program, multiple 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 performingupload/ 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>multiFileUploadServlet</servlet-name>
 <servlet-class>r4r.servlet.multiFileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
 <servlet-name>multiFileUploadServlet</servlet-name>
 <url-pattern>/multiFileUploadServlet</url-pattern>
</servlet-mapping>
<session-config>
 <session-timeout>
  30
 </session-timeout>
</session-config>
</web-app>

Index.jsp

<%-- 
Document   : index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>r4r.co.in-servlet</title>
 </head>
 <body>
  <form>
  <h1>Access Servlet by servlet's Name!</h1>
  <a href="multiFileUploadServlet">multiFileUploadServlet</a>
  </form>
 </body>
</html>

Servlet Program

/*
 * Save as a multiFileUploadServlet.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 multiFileUploadServlet 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=\"multiFileUploadServlet\
              " method=\"POST\" enctype=\"multipart/form-data\">");
out.println("<BR> Select File_1: <input type=\"file\
               " name=\"myFile_1\" value=\"\" size=\"30\" />");
out.println("<BR> Select File_2: <input type=\"file\
    " name=\"myFile_2\" value=\"\" size=\"30\" />");
out.println("<BR> Select File_3: <input type=\
        "file\" name=\"myFile_3\" value=\"\" size=\"30\" />");
out.println("<BR> Select File_4: <input type=\"file\"
name=\"myFile_4\" value=\"\" size=\"30\" />");
out.println("<BR> Select File_5: <input type=\
        "file\" name=\"myFile_5\" 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 {
out.println("File Can't Upload : " + HttpServletResponse.SC_BAD_REQUEST);
}
}
} catch (FileUploadException ex) {
Logger.getLogger(uploadFileServlet.class.getName())
	 .log(Level.SEVERE, "A FileUploadException generate", ex);
} finally {
out.close(); //close text-output stream
}
}
}

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