Could not parse multipart servlet request, nested exception is org.apache.commons.fileupload.FileUploadException
Asked Answered
B

3

8

I am getting error when i uploading 10 MB Size of csv file in Spring by using CommonsMultipartResolver library. I have done following setting in xml file Xml File Confi :

 <beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<beans:property name="maxUploadSize" value="99971520" /> <!-- 99MB -->

<!-- max size of file in memory (in bytes) -->
<beans:property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->

Controller Code:

 @RequestMapping(value="/uploadForm",method = RequestMethod.POST)
public @ResponseBody  String  uploadForm1(@ModelAttribute("admin") BillingAndRecon  billingandrecon,@RequestParam String id,BindingResult result,Principal principal,@RequestParam MultipartFile file,HttpSession session) throws ServiceException, DaoException, IllegalStateException, IOException {


    File uploadFile = null;
    String msg = "";

    if (!file.getOriginalFilename().equals("")) {

        logger.info("Before  Multipart file get path >> ");
        BillingAndReconServiceImpl asi = (BillingAndReconServiceImpl) this.billingAndReconService;// not correct!!
        String uploadDirectoryPath = asi.getUploadDirectoryPath(); // not correct!!

        uploadFile = new File( uploadDirectoryPath + file.getOriginalFilename());
        logger.info("Before  Multipart file get path uploadDirectoryPath >> "+uploadDirectoryPath);
        file.transferTo(uploadFile);
    }
}

Form Page:

<form:form action="./uploadForm" method="post" enctype="multipart/form-data" ModelAttribute=="admin">
          <input type="file" name="file" />
          <input type="text" name="id" />
           </form:form>

But I am not understanding what is issue. I tried to set up size and setting header also enctype="multipart/form-data", but yet not resolved.

Given below are error:

org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found] with root cause org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:954)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:139)
at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1047)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:892)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Blocker answered 11/5, 2015 at 6:1 Comment(0)
P
2

As @ChristianMaioliM requested in comment, added more details about The problem in your code is the BindingResult parameters not following the model object.

The Errors or BindingResult parameters have to follow the model object that is being bound immediately as the method signature might have more than one model object and Spring will create a separate BindingResult instance for each of them so the following sample won’t work

Refer docs Invalid ordering of BindingResult and @ModelAttribute

To resolve, change your controller method handler signature to follow parameter ordering between BindingResult & model object like:

From:

@RequestMapping(value="/uploadForm",method = RequestMethod.POST)
public @ResponseBody  String  uploadForm1(@ModelAttribute("admin") BillingAndRecon  billingandrecon,@RequestParam String id,BindingResult result,Principal principal,@RequestParam MultipartFile file,HttpSession session) throws ServiceException, DaoException, IllegalStateException, IOException {

To:

@RequestMapping(value="/uploadForm",method = RequestMethod.POST)
public String  uploadForm1(
            @ModelAttribute("admin") BillingAndRecon billingandrecon, 
            BindingResult result,
            Principal principal,
            HttpSession session) throws ServiceException, DaoException, IllegalStateException, IOException {
  //do file save here
  return "some-view-name";
}

and in BillingAndRecon class add mulitpart/binding fields like:

public class BillingAndRecon {
  private MultipartFile file;
  private String id;

  no-arg constructor;
  getters;
  setters;
}

Note: BindingResult argument should be after immediate of @ModelAttrubiute/@RequestBody

and jsp form:

<form:form action="${pageContext.request.contextPath}/uploadForm"  
   method="post" 
   enctype="multipart/form-data" 
   modelAttribute="admin">
      <input type="file" name="file" />
      <form:input path="id" />
</form:form>

and don't forget to add for binding instance in GET handler like:

@RequestMapping(value="/uploadForm",method = RequestMethod.GET)
public String uploadFormView(Model model){
  model.addAttribute("admin", new BillingAndRecon());
  return "your-upload-view-name";
}
Poster answered 11/5, 2015 at 7:45 Comment(3)
not yet resolve issue. Still today I am facing issue.Can You please provide any other solition. I track my contentType I am getting null in my servlets filter all IE broser why?Blocker
Please explain your answer, don't just post "do this", otherwise other people with a similar problem won't get the idea behind your implementation.Harebell
@ChristianMaioliM. answer edited to add explanation in details.Poster
A
0

Some times if there are any application specific filters in the filter chain and if they are closing the stream you can get this Exception. From the Exception stacktrace, find if any application specific filters are present and disable them and check

Adulterous answered 13/1, 2022 at 5:16 Comment(0)
E
-1

org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: Stream closed

Worked fine on Spring Boot 2.1.12, failed after upgrade to 2.2.4 (both versions run the same embedded Tomcat 9.0.30).

The root cause was that we were using logback-access filter that logs requests and responses. The filter wrapped HttpServletRequest with a caching wrapper and closed the input stream before passing the request along the filter chain. This caused an issue when javax.servlet.http.HttpServletRequest#getParts was called, as that call is delegated to the original Tomcat's request (with a now-closed input stream), which then results in the "stream closed" exception.

The Spring change that triggered this issue is hiddenHttpMethodFilter no longer being present in the filter chain. Previously this filter would be one of the first filters to be called, and it would call HttpServletRequest#getParameter, which in turn would make Tomcat's request implementation parse multipart content and store the parts in the object (so that later calls to #getParts would use that and not try to parse them again).

I reported this to Logback: https://jira.qos.ch/browse/LOGBACK-1503

Workaround - call HttpServletRequest#getParameter before passing the request to logback's filter (see LOGBACK-1503 for code), to force Tomcat to parse and store request parts while input stream is still open.

Earful answered 7/6, 2020 at 16:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.