If the version of your Servlet Container or Server or Engine < 3.0 (like 2.5 or earlier) , you may want to take advantage of the third-party Library Apache Commons FileUpload. Although the file implied an use for uploaded Files, it also deals effectually with uploaded posted Data from POST-Methods like it explained here.
the Servlet API, from the version 3.0 offers some calls in oder to deal with posted Data, with was sent within a POST-Request. the only requirement is that the MIME-Type encoding of your entity content is "multipart/form-data".
then your can retrieve each "part" of your content using either:
getPart(String partName): where "partName" is the name of a part of your Multicontent entity.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
String partName = "type"; // or "data"
Part part = request.getPart(partName);
// read your StringBody type
BufferedReader reader = new BufferedReader( new InputStreamReader(part.getInputStream()));
String line ="";
while((line=reader.readLine())!=null)
{
// do Something with a line
System.out.println(line);
}
// or with a binary Data
partName="data";
part = request.getPart(partName);
// read your FileBody data
InputStream is = part.getInputStream();
// do Something with you byte data
is.read();
// is.read(b);
// ..
}
getParts():
it achieves the same results as getPart(partName), whereas the given data here a collection of all part of the sent data. to retrieve each par of the Part of this collection, just use thread-safe iteration over the collection:
Iterator<Part> iterator = request.getParts().iterator();
Part parts = null;
while (iterator.hasNext()) {
parts = (Part) iterator.next();
//rest of the code block removed
}
}
Because the getPart()/getParts() only works beginning at the Servlet 3.0 version, you'll make sure to use the supporting Servlet container and/or upgrade your current Servlet Container. some Server or Servlet container that supports 3.0:
- tomcat 7.0:
- Jboss Web
- Resin