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.