8

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 !?

codemaniac143
  • 1,241
  • 2
  • 11
  • 18
user2115378
  • 931
  • 3
  • 14
  • 22
  • check the @ http://stackoverflow.com/questions/20162474/how-do-i-receive-a-file-upload-in-spring-mvc-using-both-multipart-form-and-chunk – JQuery Guru Mar 14 '14 at 14:47
  • But this helps me not with the configuration, i have updated my first post!! and added a new MultipartFilter and a StandardServletMultipartResolver is this correct? But i get still an error.. See Edit2 in my first post – user2115378 Mar 14 '14 at 15:44
  • I have this exact same issue. Were you able to fix it? – Vivin Paliath Aug 03 '14 at 23:42

2 Answers2

1

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.

Community
  • 1
  • 1
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
0
  1. I had the same issue, and it turned out that it was due to the StandardServletMultipartResolver. Changed it to org.springframework.web.multipart.commons.CommonsMultipartResolver See stackoverflow post from where I got this solution

  2. This may not be related to the problem presented in this post, but may help. With DEBUG turned on, I could see this DEBUG message in the logs:- "Request is already a MultipartHttpServletRequest - if not in a forward, this typically results from an additional MultipartFilter in web.xml"

Got rid of this by removing the MultipartFilter from the array of filters in getServletFilters(). MultipartFilter mpf=new MultipartFilter();

Community
  • 1
  • 1
Lijo Jacob
  • 1,241
  • 1
  • 10
  • 9