Uploading Files using servlets and simple HTML

In adding or uploading file, some developers need to add some third party library, to accomplish the uploading to any server location.

But here below, I will illustrate to you example of code snippets that must be done to upload successfully to any server  directory.

Assuming that you have already tomcat server 5.0 or latest version of tomcat.

e.g:

Upload Project

1

index.html

Insert title here

<!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>Insert title here</title>
</head>
<body>
<form action=”upload” method=”post” enctype=”multipart/form-data”>
	File: <input type=”file” name=”uploadFile”/><br/>
	<input type=”submit” value=”submit”/>
</form>
</body>
</html>
<form action="”upload”" enctype="”multipart/form-data”" method="”post”">
	File: <input name="”uploadFile”/" type="”file”"/>
	<input type="”submit”" value="”submit”/"/>
</form>

After we have servlet called

BaseServlet.java that just extends HtttpServlet

UploadController.java

package web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import web.base.BaseServlet;

@WebServlet(“/upload”)
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, maxFileSize = 1024 * 1024 * 10, maxRequestSize = 1024 * 1024 * 50)
public class UploadController extends BaseServlet {
	/**
	 * Name of the directory where uploaded files will be saved, relative to
	 * the web application directory.
	 */
	private static final String SAVE_DIR = “uploadFiles”;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	        // gets absolute path of the web application
		String appPath = req.getServletContext().getRealPath(“”);
	        // constructs path of the directory to save uploaded file
		String savePath = appPath + File.separator + SAVE_DIR;
		savePath = “D:\\angelo”+File.separator + SAVE_DIR;
	        // creates the save directory if it does not exists
		File fileSaveDir = new File(savePath);
		if (!fileSaveDir.exists()) {
			fileSaveDir.mkdir();
		}
		for (Part part : req.getParts()) {
			String fileName = extractFileName(part);
			part.write(savePath + File.separator + fileName);
		}
		req.setAttribute(“title”, “upload response”);
		req.setAttribute(“message”, “Upload has been done successfully !”);
		getServletContext().getRequestDispatcher(“ / pages / message.jsp”).forward(req, resp);
	}

	/**
	 * Extracts file name from HTTP header content-disposition
	 */
	private String extractFileName(Part part) {
		String contentDisp = part.getHeader(“content - disposition”);
		String[] items = contentDisp.split(“;”);
		for (String s : items) {
			if (s.trim().startsWith(“filename”)) {
				return s.substring(s.indexOf(“ =”) + 2,s.length() - 1);
			}
		}
		return “”;
	}
}

The UploadController servlet class does the uploading of file in server location, then redirect it to messages.jsp page.

Redirected it to result page:

messages.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
    pageEncoding=”ISO-8859-1″%>
<!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>${requestScope.title}</title>
</head>
<body>
<h2>${requestScope.message}</h2>
</body>
</html>
${requestScope.title}
<h2>${requestScope.message}</h2>

Then that’s it were done.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.