Spring MVC file upload - Unable to process parts as no multi-part configuration has been provided

允我心安 提交于 2019-12-04 02:57:15

Actually you don't need any filter on the web.xml in order to upload your multipart file with Spring MVC. I've the same configuration in my project and it worked (${spring.version} = 4.3.4.RELEASE):

POM

     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!-- Apache Commons FileUpload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.2</version>
    </dependency>

    <!-- Apache Commons IO -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>

HTML

    <form method="POST" enctype="multipart/form-data" action="uploadAction">
        <table>
            <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
            <tr><td></td><td><input type="submit" value="Upload" /></td></tr>
        </table>
    </form>

Spring context

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000"/>
</bean>

Spring controller

@PostMapping("/uploadAction")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
            RedirectAttributes redirectAttributes) {

        File out = new File("outputfile.pdf");
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(out);

            // Writes bytes from the specified byte array to this file output stream 
            fos.write(file.getBytes());
            System.out.println("Upload and writing output file ok");
        } catch (FileNotFoundException e) {
            System.out.println("File not found" + e);
        } catch (IOException ioe) {
            System.out.println("Exception while writing file " + ioe);
        } finally {
            // close the streams using close method
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ioe) {
                System.out.println("Error while closing stream: " + ioe);
            }

            //storageService.store(file);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded " + file.getOriginalFilename() + "!");

            return "redirect:/";
        }
    }

It is straight forward from the exception that no multi-part configuration is found. Though you have provided multipartResolver bean.

The problem is that while specifying the MultipartFilter before the Spring Security filter, It tries to get the multipartResolver bean but can't find it. Because it expect the bean name/id as filterMultipartResolver instead of multipartResolver.

Do yourself a favor. Please change the bean configuration like following -

<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000"/>
</bean>
Martín Straus

None of the answers address the issue properly. As per Tomcat documentation, on the configuration of allowCasualMultipartParsing:

Set to true if Tomcat should automatically parse multipart/form-data request bodies when HttpServletRequest.getPart* or HttpServletRequest.getParameter* is called, even when the target servlet isn't marked with the @MultipartConfig annotation (See Servlet Specification 3.0, Section 3.2 for details). Note that any setting other than false causes Tomcat to behave in a way that is not technically spec-compliant. The default is false.

So, what's the compliant way? Reading the official JEE 6 tutorial gives a hint. If you want to use a spec-compliant way with Servlet 3 or newer, your servlet must have a MultipartConfig. You have three choices, depending on how you configure your servlet:

  • With programmatic configuration: context.addServlet(name, servlet).setMultipartConfig(new MultipartConfigElement("your_path").
  • With annotations, annotate the servlet's class with @javax.servlet.annotation.MultipartConfig.
  • With XML configuration, add this to the WEB-INF/web.xml descriptor, in the section of your servlet:

    <multipart-config>
         <location>/tmp</location>
         <max-file-size>20848820</max-file-size>
         <max-request-size>418018841</max-request-size>
         <file-size-threshold>1048576</file-size-threshold>
    </multipart-config>
    

I have something similar, but what i did is just send a file without mapping it with any attribute in my model, in your case i would modify this:

<div class="form-group">
    <div class="col-lg-3">
        <label for="photo">Artist photo:</label>
        <input type="file" id="photo" name="file"/>
    </div>
</div>

In your controller

@RequestMapping(value = "/newArtist", method = RequestMethod.POST)
public String addArtist(@ModelAttribute("artist") @Valid Artist artist, BindingResult result,
    @RequestParam("file") MultipartFile file) throws IOException
//Here read the file and store the bytes into your photo attribute
...

Add In your config file as:

@Bean(name = "multipartResolver")
public CommonsMultipartResolver CanBeAnyName() { 
//configuration

}

Had the same issue in a Spring Boot application, this exceptions occur several times:

  • org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is
  • java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field multipartFile exceeds its maximum permitted size of 1048576 bytes

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field multipartFile exceeds its maximum permitted size of 1048576 bytes.

Get rid of the tomcat exception with this, with copy catting from http://www.mkyong.com/spring-boot/spring-boot-file-upload-example/

Tomcat large file upload connection reset. Need to let {@link #containerCustomizer()} work properly, other wise exception will occur several times, RequestMapping for uploadError will fail.

@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {

    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();

    tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
        if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
            //-1 means unlimited
            ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
        }
    });

    return tomcat;

}

For those who get the same exception for PUT method handlers: use POST instead. PUT is incompatible with the multi-part.

More details can be found in the respective answer

If you are using Tomcat 8.
Configure the following in Tomcat's conf/context.xml

  • Add allowCasualMultipartParsing="true" attribute to context node
  • Add <Resources cachingAllowed="true" cacheMaxSize="100000" /> inside context node
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!