Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 440
user2115378 Avatar asked Mar 14 '14 13:03

user2115378


People also ask

How to upload files from angular 12 to Spring Boot Server?

Run Spring Boot Server with command: mvn spring-boot:run. Refresh the project directory and you will see uploads folder inside it. Open Browser with url http://localhost:8081/ and check the result. Today we’re learned how to build an example for upload Files from Angular 12 to Spring Boot server.

How to configure servlet multipart with Spring Boot?

– application.properties contains configuration for Servlet Multipart. – uploads is the static folder for storing files. – pom.xml for Spring Boot dependency. Use Spring web tool or your development tool ( Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project. Then open pom.xml and add these dependencies:

Is it possible to model multiple file upload using spring resttemplate?

Obviously, the request URL should refer to endpoint for multiple file upload: It's always possible to model single file upload using the multiple file upload. 7. Conclusion In conclusion, we saw a case of MultipartFile transfer using Spring RestTemplate.

What is filesstorageservice in Spring Boot application?

Our Spring Boot Application will provide APIs for: Let me explain it briefly. – FileInfo contains information of the uploaded file. – FilesStorageService helps us to initialize storage, save new file, load file, get list of Files’ info, delete all files.


1 Answers

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.

like image 105
Vivin Paliath Avatar answered Oct 27 '22 14:10

Vivin Paliath