1

I created a REST Upload service using Sppring boot :

@CrossOrigin
@RestController
@RequestMapping("/upload")
public class FileUploadHandler {

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

        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(file.getName() + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + file.getName() + " into " + file.getName() + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + file.getName() + " => " + e.getMessage();
            }
        } else {

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

            return "Some error... ";
        }
    }

}

I am using an Angular2 + webpack client to consume the service. Problem is that i get a CROS block when I try access the service.

XMLHttpRequest cannot load http://localhost:8080/kti-cms-spring/upload/doUpload. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ac1068:8080' is therefore not allowed access.

I am using glassfish4 as an application server.

My configuration:

@Configuration
@ComponentScan("de.awinta.kti.cms")
public class MainConfig {

    @Bean
    public FilterRegistrationBean corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // likely you should limit this to specific origins
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(Boolean.TRUE);
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;

    }
}

App entry point

    @SpringBootApplication
public class KtiCmsApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
     SpringApplication.run(KtiCmsApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);
    }

    private static Class<KtiCmsApplication> applicationClass = KtiCmsApplication.class;
}

I am out of ideas how to get this working, and was thinking to try plain old JAX-RS for service exposure. Maybe somebody here has an idea on how to get this working with spring.

pxr_64
  • 510
  • 1
  • 8
  • 23

1 Answers1

0

I don't see a particular error in your code but maybe the following code snippet will help you to get CORS running. This is how I set up cors in a spring boot project with Ember.js as Frontend.

Try to add a Configuration class CorsConfig to your project with a CorsFilter Bean:

package your.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

public CorsConfig() {
}

@Bean
public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // likely you should limit this to specific origins
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("HEAD");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("DELETE");
    config.addAllowedMethod("PATCH");
    config.setAllowCredentials(Boolean.TRUE);
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
 }
}

Add @CrossOriginto your Controllers (like you already have)

These doc and SO question helped me to get this running:

Community
  • 1
  • 1
Pascal
  • 1,984
  • 1
  • 21
  • 25
  • Hey. Thanks for the feedback. After adding the configuration class it is still saying the same error. I am sure but, do you think it is possible that the Glassfish does not load the app correctly? – pxr_64 Oct 05 '16 at 08:31
  • I'm sorry, I don't know much about about Glassfish and couldn't tell from your example. Just to be sure, you have to enable auto configuration (via EnableAutoConfiguration or @SpringBootApplication annotation) in Spring boot – Pascal Oct 05 '16 at 10:12
  • Adding annotations does not help :(. I added the app configuration and entry point to the issue, maybe it helps. – pxr_64 Oct 05 '16 at 11:17