Spring MVC Processing multipart form data

2019-09-10 21:24发布

Using Craig Walls book "Spring in Action, 4th Edition", 7.2. Processing multipart form data

The code does not run no matter what path you try. I even tried C:\something. Don't you have to create the directory first?

When I run the code, I get the error below:

root cause org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [C:\Users\jokra_000\sts-bundle\pivotal-tc-server-developer-3.1.1.RELEASE\base-instance\work\Catalina\localhost\spittr\tmp\spittr\uploads] is not valid

Has anyone successfully uploaded an image file as outlined in Chapter 7? It seems there's far more to it than what's described, as the code Craig supplied does not run. Instead it crashes and will not upload a file.

Any suggestions on how to implement MultipartFile and the Path?

Craig's suggestion:

in AbstractAnnotationConfigDispatcherServletInitializer:

@Override 
protected void customizeRegistration(Dynamic registration) { 
 registration.setMultipartConfig( 
 new MultipartConfigElement("/tmp/spittr/uploads", 2097152, 4194304, 0)); 
} 

in Controller processRegistration:

MultipartFile profilePicture = spitterForm.getProfilePicture(); 
profilePicture.transferTo(new File("/tmp/spittr/" + spitter.getUsername() +         ".jpg")); 

1条回答
霸刀☆藐视天下
2楼-- · 2019-09-10 21:43

It worked when I did the following: I changed MultipartResolver:

 @Bean
    public MultipartResolver multipartResolver() throws IOException {
        return new CommonsMultipartResolver();
    }

and also added the dependency:

 <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.2</version>
    </dependency>

and then imported to the file that extends WebMvcConfigurerAdapter:

import org.apache.commons.fileupload.FileItemFactory;
查看更多
登录 后发表回答