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;
}