Tuesday 1 October 2013

File Upload

How to Upload Files using Java Servlets :


Hey Guys !!! Welcome again to my blog. Today I came to you with the Java Code of uploading files using Java Servlets. This post is very useful for all of you who wants to make a web application using Java Servlets & JSP. Almost every web application needs to upload the files which can be anything. So, if you want to prepare a web application using Java Servlets, you must know this concept of file uploading.

Some jar files need to be downloaded before we get start. The required jar files are given below :-
  1. commons-fileupload-1.2.2.jar
  2. commons-io-2.4.jar

Now set the classpath of the jar files you have downloaded from the link given above.

After setting the classpath, the only work we have to do is to code. So here we go.......

FileUpload.html :
 <html>  
 <body>  
   <h1>File Upload Form</h1>   
   <fieldset>  
     <legend>Upload File</legend>  
     <form action="FileUploadExample" method="post" enctype="multipart/form-data">  
       <label for="fileName">Select File: </label>  
       <input id="fileName" type="file" name="fileName" size="30" multiple="multiple" /><br/>        
       <input type="submit" value="Upload"/>  
     </form>  
   </fieldset>  
 </body>  
 </html>  


FileUploadExample.java :
 import java.io.File;  
 import java.io.IOException;  
 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.FileUploadException;  
 import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
 import org.apache.commons.fileupload.servlet.ServletFileUpload;  
 public class FileUploadExample extends HttpServlet {  
      @Override  
     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
          throws ServletException, IOException {  
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
         response.setContentType("text/html");  
          PrintWriter out = response.getWriter();  
        if (isMultipart) {  
           // Create a factory for disk-based file items  
           FileItemFactory factory = new DiskFileItemFactory();  
           // Create a new file upload handler  
           ServletFileUpload upload = new ServletFileUpload(factory);  
          try {  
             // Parse the request  
             List /* FileItem */ items = upload.parseRequest(request);  
            Iterator iterator = items.iterator();  
            while (iterator.hasNext()) {  
              FileItem item = (FileItem) iterator.next();  
              if (!item.isFormField())  
               {  
                String fileName = item.getName();      
                String root = getServletContext().getRealPath("/");  
                File path = new File(root + "/uploads");  
                if (!path.exists())  
                 {  
                  boolean status = path.mkdirs();  
                }  
                File uploadedFile = new File(path + "/" + fileName);  
                System.out.println(uploadedFile.getAbsolutePath());  
                 if(fileName!="")  
                item.write(uploadedFile);  
                 else  
                   out.println("file not found");  
                 out.println("<h1>File Uploaded Successfully....:-)</h1>");  
              }  
               else  
               {  
                 String abc = item.getString();  
 //        out.println("<br><br><h1>"+abc+"</h1><br><br>");  
               }  
            }  
          } catch (FileUploadException e) {  
                out.println(e);  
          } catch (Exception e) {  
                out.println(e);  
          }  
        }  
         else  
         {  
           out.println("Not Multipart");  
         }  
      }  
 }  


Now you can compile & run the above codes using Apache Tomcat Server or any other server. the uploaded files will be in a folder named "uploads" inside the web-apps directory in Apache Tomcat folder.



I hope you will find this post helpful in various JAVA Projects. If you face any difficulty in this post you can ask it by commenting here. i will reply as soon as possible.

For more java codes................ stay connected  :-)