skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Friday, October 5, 2012

Get MultiPart Parameters Using MultipartParser

Posted by Raju Gupta at 12:30 PM – 0 comments
 

This code extract both files & non-file parameters from the request using MultipartParser.


 /**
  * Example  getMultiPartParams()
  * Method for extracting parameters from multipart request.
  *
  * @param req javax.servlet.http.HttpServletRequest
  *
  * @return java.util.HashMap
  *
  * @throws Exception
  */
 public HashMap getMultiPartParams(HttpServletRequest req) throws Exception
 {
  String fileName = "";
  String absFilePath = null;
  File fp = null;
  HashMap requestMap = new HashMap();
  try
  {
   //create MultipartParser object for the request.
   MultipartParser mp = new MultipartParser(req, 10 * 1024 * 1024);
   Part part = null;
   int i = 0;
   File dir = null;
   String value = null;
   //iterate for getting value for all part
   while ((part = (Part) mp.readNextPart()) != null)
   {
    //Check if the part is file or parameter
    if (part.isFile())
    {
     String filePath = "give the location for storing the file";
     //Get time in millisecond for creating unique path dynamically.
     long time = System.currentTimeMillis() + 1;
     //Get the file part from the multipart request
     FilePart filePart = (FilePart) part;
     //Get the file name from the FilePart object
     fileName = (String) filePart.getFileName();
     //Get InputStream
     InputStream fileStream =
      (InputStream) filePart.getInputStream();
     StringBuffer fileRef = new StringBuffer();
     //Build absolute path dynamically
     fileRef
      .append(filePath)
      .append(File.separator)
      .append(time)
      .append(File.separator)
      .append(fileName);
     dir = new File(String.valueOf(fileRef));
     //Create directories
     dir.mkdirs();
     //Delete the last sub directory
     dir.delete();
     //create the file.
     filePart.writeTo(dir);
     //Put the file ref to a HashMap
     requestMap.put(
      fileName,
      String.valueOf(fileRef));
    }
    else
    {
     //Get the name of the parameter
     String paramname = part.getName();
     //Get ParamPart from the multipart request
     ParamPart paramPart = (ParamPart) part;
     //Get the parameter values
     value = new String(paramPart.getStringValue());
     //Put this parameter to a HashMap
     requestMap.put(paramname, value);
    }
   }
  }
  catch (Exception ex)
  {
   throw ex;
  }
  return requestMap;
 }


Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger