Passing parameters along with a multipart/form-data upload form (Java Http Post Upload)

元气小坏坏 提交于 2019-12-18 05:23:26

问题


I have a code base which currently uploads file using Post and has enctype as multipart/form-data. Now I need to include some form items i.e. some parameters will also be passed along with the file upload. I have my html form created out but I cannot use request.getParameter because it is a multipart form. Could anyone suggest me how do I pass parameters along with my upload file. I am providing the codes below. Please suggest me how to get around based on compatibility of my codes

if (!ServletFileUpload.isMultipartContent(request)) {
  throw new CustomUploadException("Not a file upload request");
}

ServletFileUpload  upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);

while (iter.hasNext())
{
  FileItemStream item = iter.next();

  if (item.isFormField() == false && 
      item.getFieldName().equalsIgnoreCase("xmlfile"))
  {
      String fileName = item.getName();
      myBean.setFileName(fileName );
  }

}

回答1:


If isFormField on FileItemStream returns true it's a normal field. You can use openStream and read the contents into a String.

Something like this:

FileItemStream item = iter.next();
if(item.isFormField()) {
   // Normal field
   String name = item.getFieldName();
   String value = Streams.asString(item.openStream());
} else {
   // File
}

Streams.asString takes a second parameter which is the charset encoding to use, you might need to specify one that is suitable for your site.




回答2:


To send a parameter with a FileUpload it just needs to be added in the URL within the setAction method As follows:

formPanel.setAction("<ProjectURL>/<YourServletName>?<YourParameterName>="+parameter);

And in your servlet simply get the parameter as follows:

req.getParameter("<YourParameterName>");

Hope it helps ;-)




回答3:


Similar solutions:

FileItemStream item = iter.next();
if(item.isFormField()) {
    String value = item.getString();
}

or

FileItemStream item = iter.next();
if(item.isFormField()) {
   InputStream name = item.getInputStream();
   String value = Streams.asString(name);
}


来源:https://stackoverflow.com/questions/6536947/passing-parameters-along-with-a-multipart-form-data-upload-form-java-http-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!