public class UploadServlet extends HttpServlet { //default maximum allowable file size is 1000k static final int MAX_SIZE = 1024000; //instance variables to store root and success message String rootPath, successMessage; /** * init method is called when servlet is initialized. */ public void init(ServletConfig config) throws ServletException { super.init(config); //get path in which to save file rootPath = config.getInitParameter("RootPath"); if (rootPath == null) { rootPath = "/"; } /*Get message to show when upload is complete. Used only if a success redirect page is not supplied.*/ successMessage = config.getInitParameter("SuccessMessage"); if (successMessage == null) { successMessage = "File upload complete!"; } } /** * doPost reads the uploaded data from the request and writes * it to a file. */ public void doPost(HttpServletRequest request, HttpServletResponse response) { ServletOutputStream out=null; DataInputStream in=null; FileOutputStream fileOut=null;
try { /*set content type of response and get handle to output stream in case we are unable to redirect client*/ response.setContentType("text/plain"); out = response.getOutputStream();
//get content type of client request String contentType = request.getContentType(); out.println("\ncontentType= " + contentType);
//make sure content type is multipart/form-data if(contentType != null && contentType.indexOf( "multipart/form-data") != -1) { //open input stream from client to capture upload file in = new DataInputStream(request.getInputStream()); //get length of content data int formDataLength = request.getContentLength(); out.println("\nContentLength= " + formDataLength);
//allocate a byte array to store content data byte dataBytes[] = new byte[formDataLength]; //read file into byte array int bytesRead = 0; int totalBytesRead = 0; int sizeCheck = 0; while (totalBytesRead < formDataLength) { //check for maximum file size violation sizeCheck = totalBytesRead + in.available(); if (sizeCheck > MAX_SIZE) { out.println("Sorry, file is too large to upload."); return; }