Servlet File Upload

Servlet File Upload


Posted in : Java Posted on : May 24, 2012 at 6:41 PM Comments : [ 0 ]

In this tutorial you will learn about uploading many files at once using servlet

Servlet File Upload

To upload file in servlet, following are some steps

  • Create FileItemFactory instance
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    	
  • By using fileItemFactory instace get the ServletFileUpload object as
    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    
  • Now get the list of all files by parsing the request
    List fileItems = servletFileUpload.parseRequest(request);
    
  • Create the InputStream and OutputStream instance by using the fileItems as
    OutputStream outputStream = new FileOutputStream(fileItem.getName());
    InputStream inputStream = fileItem.getInputStream();
    
  • Innitiate a byte array and read bytes from input stream and write it to the output stream
    int readBytes = 0;
    byte[] buffer = new byte[10000];
    while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
    	outputStream.write(buffer, 0, readBytes);
    }
    

The complete servlet code is given below

MyServlet.java

package devmanuals.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class MyServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		FileItemFactory fileItemFactory = new DiskFileItemFactory();
		ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
		try {
			List fileItems = servletFileUpload.parseRequest(request);
			Iterator iterator = fileItems.iterator();
			while (iterator.hasNext()) {
				FileItem fileItem = iterator.next();
				boolean formFied = fileItem.isFormField();
				if (formFied) {
					out.println("regular form field"
							+ fileItem.getFieldName());
				} else {
					String fileName = request.getRealPath("") + "/images/"+ fileItem.getName();
					OutputStream outputStream = new FileOutputStream(fileName);
					InputStream inputStream = fileItem.getInputStream();
					
					int readBytes = 0;
					byte[] buffer = new byte[10000];
					while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
						outputStream.write(buffer, 0, readBytes);
					}
					outputStream.close();
					inputStream.close();
					if(fileItem.getName()!= null){
						out.println("<td><img width='100' heigth='100' src="+ request.getContextPath() + "/images/"+ fileItem.getName() + "></td>");
					}					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
}

Following is the file upload form

<html>
<head>
<title>My form</title>
<script type="text/javascript">
var displayDiv = false;
function viewFileUpload() {
var divElement = document.getElementById("imageblock");
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");

if (displayDiv) {
divElement.style.display = "block";
plus.style.display = "none";
minus.style.display = "block";
displayDiv = false;
} else {
divElement.style.display = "none";
plus.style.display = "block";
minus.style.display = "none";
displayDiv = true;
}
}
function makeInvisibleDiv() {
var divElement = document.getElementById("imageblock");
var imageElement = document.getElementById("minus");
divElement.style.display = "none";
imageElement.style.display = "none";
displayDiv = true;
}
</script>
</head>
<body onLoad="makeInvisibleDiv()">
<center>
<form action="myservlet.html" method="post"
enctype="multipart/form-data">
<table>
<tr>
<td><input type="file" name="image" id="image" /></td>
<td><img src="./img/plus.png" id="plus" width="30" height="30" onclick= "viewFileUpload();">
<img src="./img/minus.png" id="minus" width="25" height="25" onclick="viewFileUpload();">
</td>
</tr> 
</table>
<div id="imageblock">
<input type="file" name="image1" id="image1" /><br />
<input type="file" name="image2" id="image2" /><br />
<input type="file" name="image3" id="image3" /><br />
<input type="file" name="image4" id="image4" />
</div>
<input type="submit" value="Add" /></form>
</center>
</body>
</html>


When you run this application it will display message as shown below:


Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics