Sunday, February 5, 2012

comment_icon 0 Uploading a File in JSP

This Tutorial tell that how to upload a File using JSP .
This tutorial is based on the tutorial i found on tutorialspoint .
I updated the code according to RAD so you can easily work on it .
few things to take care about it are
1. copy the class packages from src folder or you can find in links given bellow

Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from http://commons.apache.org/fileupload/.

FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from http://commons.apache.org/io/.

2.Make sure you have created directories temp and upload in webcontet folder of your project in
advance.
3. change the filepath to to project workspace use \\ in place of \

4. Download Complete Source


INDEX.JSP

File Upload:

Select a file to upload:




UPLOAD.JSP

<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>


<%
   File file,file1 ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   ServletContext context = pageContext.getServletContext();
  String dir = request.getServletPath();
    int slashIndex = dir.lastIndexOf('/');
    dir = slashIndex != -1 ? dir.substring(0, slashIndex+1) : "";
     String temppath=  application.getRealPath(dir + "\\temp\\"); //temp directory  crete two directory in web content folder
   dir = application.getRealPath(dir + "\\upload\\"); /* upload directoy if it is not saved then file will not get updated until you restart your RAD/eclipse
   */
   //dir=application.getContextPath();
   //String filePath = dir;
  /*original file path on system Dir path will store image till ur application is running on server */
   String filePath = "C:\\Documents and Settings\\Abhi\\IBM\\rationalsdp\\workspace\\uploadtest\\WebContent\\upload\\";
   // Verify the content type
   String contentType = request.getContentType();
   if ((contentType.indexOf("multipart/form-data") >= 0)) {

      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File(temppath));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );
      try{ 
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);

         // Process the uploaded file items
         Iterator i = fileItems.iterator();

         out.println("");
         out.println("");
         out.println("JSP File upload");  
         out.println("");
         out.println("");
         while ( i.hasNext () ) 
         { dir=dir+"\\";
         
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () ) 
            {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
            file = new File( filePath + 
            fileName.substring( fileName.lastIndexOf("\\"))) ;
           file1=new File( dir +
            fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
            file = new File( filePath + 
            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            file1 = new File( dir + 
            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            fi.write(file1);
            out.println("Uploaded Filename: " + dir + " "+
            fileName + "
");
            }
         }
         out.println("");
         out.println("");
      }catch(Exception ex) {
         System.out.println(ex);
      }
   }else{
      out.println("");
      out.println("");
      out.println("Servlet upload");  
      out.println("");
      out.println("");
      out.println("No file uploaded
"); out.println(""); out.println(""); } %>