How to read other parameters in multipart form using Apache Commons

I have a file upload form that is sent back to the servlet (using multipart / form-data encoding). In the servlet, I'm trying to use Apache Commons to handle loading. However, I also have other fields in the form that are just fields. How can I read these parameters from the request?

For example, in my servlet, I have code like this for reading in the uplaoded file:

// Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request Iterator /* FileItem */ items = upload.parseRequest(request).iterator(); while (items.hasNext()) { FileItem thisItem = (FileItem) items.next(); ... do stuff ... } 
+4
source share
3 answers

You can try something like this:

 while (items.hasNext()) { FileItem thisItem = (FileItem) items.next(); if (thisItem.isFormField()) { if (thisItem.getFieldName().equals("somefieldname") { String value = thisItem.getString(); // Do something with the value } } } 
+8
source

Took me a few days to find out, but here it is, and it works, you can read multi-part data, files and parameters, here is the code:

  try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while(iterator.hasNext()){ FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if(item.isFormField()){ if(item.getFieldName().equals("vFormName")){ byte[] str = new byte[stream.available()]; stream.read(str); full = new String(str,"UTF8"); } }else{ byte[] data = new byte[stream.available()]; stream.read(data); base64 = Base64Utils.toBase64(data); } } } catch (FileUploadException e) { e.printStackTrace(); } 
+3
source

Have you tried request.getParam () again?

-2
source

All Articles