Spring Rest Multipart file upload with AngularJS (Java Config)?

11,909

If you are using Servlet 3.0, you have to configure the dispatcher servlet to support multipart as well. I was running into the exact same issue as you. I had the multipart-resolver bean configured, but I was still running into issues. Simply add the following line to your application initializer class (the one that extends WebApplicationInitializer):

dispatcher.setMultipartConfig(
        new MultipartConfigElement("/tmp", 25 * 1024 * 1024, 125 * 1024 * 1024, 1 * 1024 * 1024)
);

dispatcher is an instance of ServletRegistration.Dynamic. For more details you can read my answer to my question here.

Share:
11,909
user2115378
Author by

user2115378

Updated on June 15, 2022

Comments

  • user2115378
    user2115378 almost 2 years

    I have used spring MVC with java config and I have defined some rest-services. I used Spring as server backend and AngularJS as WebFrontend.

    I want upload from my AngularJS site one or two CSV files to my rest service. How must i configure spring with java config so that it works? I used Tomcat and a Servlet 3 Container.

    My upload rest service looks like this:

    @Controller
    @RequestMapping("Upload")
    @MultipartConfig(fileSizeThreshold=1024*1024*10,    // 10 MB
    maxFileSize=1024*1024*50,          // 50 MB
    maxRequestSize=1024*1024*100)      // 100 MB
    public class UploadController {
    
        @RequestMapping(value="/upload", method=RequestMethod.GET)
        public @ResponseBody String provideUploadInfo() {
            return "You can upload a file by posting to this same URL.";
        }
    
        @RequestMapping(value="/upload", method=RequestMethod.POST)
        public @ResponseBody String handleFileUpload(@RequestParam("name") String name, 
                @RequestParam("file") MultipartFile file){
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    BufferedOutputStream stream = 
                            new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                    stream.write(bytes);
                    stream.close();
                    return "You successfully uploaded " + name + " into " + name + "-uploaded !";
                } catch (Exception e) {
                    return "You failed to upload " + name + " => " + e.getMessage();
                }
            } else {
                return "You failed to upload " + name + " because the file was empty.";
            }
        }
    
    }
    

    Do i need a "StandardServletMultipartResolver" ? or anything else to get the upload to work ? and if so, how can i enable the multi-part upload with java config ? my config at the moment looks like this:

    public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class<?>[]{ PersistenceContext.class,AppConfig.class,SecurityConfig.class }; 
        }
    
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class<?>[] { WebConfig.class };
        }
    
        @Override
        protected String[] getServletMappings() {
            return new String[] { "/Spring/*" }; 
        }
    
        @Override
        protected Filter[] getServletFilters() {
    
            CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
            characterEncodingFilter.setEncoding("UTF-8");
    
            CorsFilter cf=new CorsFilter();
                MultipartFilter mpf=new MultipartFilter(); //MultipartFilter support
            return new Filter[] {characterEncodingFilter,cf,mpf};
    
        }
    
    
    
    
    }
    

    and WebConfig:

    @Configuration
        @EnableWebMvc
        @ComponentScan(basePackages = { "controller" })
        public class WebConfig extends WebMvcConfigurerAdapter {
    
           @Bean
    public MultipartResolver multipartResolver(){
    
            return new StandardServletMultipartResolver();
        }
    

    }

    and ApplicationConfig

    @Configuration
    public class AppConfig {
    
        @Bean
        public Test getTest(){
    
    
            return new Test();
        }
    }
    

    The Example with the upload is from this site http://spring.io/guides/gs/uploading-files/ but they used a MultiPartConfigFactory and this is from spring boot; can i use this to ? i did not use spring boot at the moment.. So What is the easiest way to get the multi-part upload working with my configuration!?

    EDIT2: I have added two things to my configuration Above the new getServletFilter looks now like this, i have added a MultipartFilter():

    @Override
        protected Filter[] getServletFilters() {
    
            CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
            characterEncodingFilter.setEncoding("UTF-8");
    
    
            CorsFilter cf=new CorsFilter();
    
            MultipartFilter mpf=new MultipartFilter(); //MultipartFilter support
    
    
            return new Filter[] {characterEncodingFilter,cf,mpf};
    
        }
    

    and in my WebConfig i have added a StandardServletMultipartResolver:

    @Bean
    public MultipartResolver multipartResolver(){
    
            return new StandardServletMultipartResolver();
        }
    

    Now i want to test it with a simple html site like this:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    
    <form method="POST" enctype="multipart/form-data"
            action="http://localhost:8081/project/Spring/Upload/upload">
            File to upload: <input type="file" name="file"><br /> Name: <input
                type="text" name="name"><br /> <br /> <input type="submit"
                value="Upload"> Press here to upload the file!
        </form>
    
    </body>
    </html>
    

    but it says "HTTP Status 400 - Required String parameter 'name' is not present". why is name not present !?