Java servlet: problem with form multipart / form-data

I have a multipart / form-data form with some fields <input type='text'> and <input type='file'> .

I am using this code

  List<FileItem> multipartItems = null; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { System.out.println("false"); } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); multipartItems = null; try { multipartItems = upload.parseRequest(request); System.out.println("true "+multipartItems.toString()); } catch (FileUploadException e) { e.printStackTrace(); } } 

to find out if the form has multi-page content. Then i use

  Map<String, String[]> parameterMap = new HashMap<String, String[]>(); for (FileItem multipartItem : multipartItems) { if (multipartItem.isFormField()) { processFormField(multipartItem, parameterMap); } else { request.setAttribute(multipartItem.getFieldName(), multipartItem); } } 

Running the first code fragment, else is executed, but at the end multipartItems is null.

For this reason, the value in the second code fragment is never executed.

I do not know why this behavior. I am using Struts 1.3.10

EDIT

How to check if struts checks a request?

If so, is there a way to disable it only for a specific form?

EDIT 2

I have a dynamic form encoded in json format. I have a bean form for json and for hidden properties. Then I parse json "manually." Everything works fine, but now I have to add input type = file fields and use the multipart / form-data enctype attribute.

To prevent parsing struts requests, I put in web.xml:

 <init-param> <param-name>multipartClass</param-name> <param-value>none</param-value> </init-param> 

But it does not work

+4
source share
2 answers

Initialize the FileItem as shown below:

  FileItem fileItem = null; 

Then call this method

  public boolean getParameters(HttpServletRequest request, PrintWriter out) { List fileItemsList = null; try { if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); try { fileItemsList = servletFileUpload.parseRequest(request); } catch (FileUploadException ex) { } String optionalFileName = ""; Iterator it = fileItemsList.iterator(); while (it.hasNext()) { FileItem fileItemTemp = (FileItem) it.next(); if (fileItemTemp.isFormField()) { // for other form fields that are not multipart // if (fileItemTemp.getFieldName().equals("commonName")) { // commonName = fileItemTemp.getString(); // } } else { if (fileItemTemp.getFieldName().equals("media_file")) { fileItem = fileItemTemp; } } } } } catch (Exception e) { } return true; } 
+2
source

I used this example to upload files using a servlet, and jsp works fine for me. Click here

The example is explained in detail, and if you encounter any problem, ask me, I used this.

+1
source

Source: https://habr.com/ru/post/1501802/


All Articles