[英]how to upload a file to spring boot using angular 7?
In order to upload a file in angular 7 for a spring boot project, I am getting 404 with error blocked by CORS policy. 为了为Spring Boot项目上传一个角度为7的文件,我得到了404错误,并且被CORS策略阻止。 the angular code:::
角度代码:::
uploadFile(file: File){
console.log("file to be uploaded...",file);
const postData = new FormData();
postData.append("file", file);
this.http.post('http://localhost:8070/postFile',postData).subscribe(data=>{
console.log("post succeessful.....",data);
});
spring boot code::: 春季启动代码:::
@CrossOrigin(origins = "*")
@PostMapping("/postFile")
public ResponseDTO postFile(@RequestParam("file") MultipartFile file) {
I have tried with @RequestPart as well here with same result.
when I try to upload the file for first time, I am getting the below log: Initializing Spring DispatcherServlet 'dispatcherServlet' Initializing Servlet 'dispatcherServlet' Completed initialization in 9 ms 当我第一次尝试上传文件时,得到以下日志:初始化Spring DispatcherServlet'dispatcherServlet'初始化Servlet'dispatcherServlet'在9毫秒内完成了初始化
After fisrt attempt , spring boot does not produce any log, however in browser I could see below log on every attempt. 经过fisrt尝试后,spring boot不会产生任何日志,但是在浏览器中,每次尝试我都可以在下面看到日志。
POST http://localhost:8070/postFile 404 Zone.js
Access to XMLHttpRequest at 'http://localhost:8070/postFile' from origin
'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Could you please suggest , how to upload a file in angular + spring boot. 您能否提出建议,如何在angular + spring boot中上传文件。
@CrossOrgin
should work, but you could also try this @CrossOrgin
应该可以,但是您也可以尝试一下
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*");
}
}
or in @SpringBootApplication
class add 或在
@SpringBootApplication
类中添加
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(Collections.singletonList("*"));
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> filterRegistration = new FilterRegistrationBean<>(new CorsFilter(source));
filterRegistration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return filterRegistration;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.