Hello Guys I'm sending a form data type request from (angular CLI 11) front-end to (spring boot) back end. In this request I want to send an image with some details.
Anyway I get 400 error when I send my request
Send( file: File, description: string, feeling: string): Observable<HttpResponse<any>> {
const body: FormData = new FormData();
body.append('file', file);
body.append('description', description);
body.append('feeling', feeling);
return this.http.post<HttpResponse<any>>(environment.baseUrl + '/api/v1/launches', body, {
observe: 'response'
});
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping(
produces = MediaType.MULTIPART_FORM_DATA_VALUE,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
)
@ResponseBody
public ResponseEntity<Object> save( @ModelAttribute LaunchBody body) throws Exception {
System.out.println("body");
try {
System.out.println(body.getFile().getContentType());
fileService.save(body.getFile());
return new ResponseEntity<>("OK :)", HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>("Something went wrong !!", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Component
public class CORSFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTION");
response.setHeader("Access-Control-Allow-Headers", "Content-type,Origin,Authorization");
super.doFilter(request, response, chain);
}
}
OK, Finally I discovered the answer. The prob was an error occurring when I creating the form data body :/ In there I've set a wrong value to the file element. In component.ts,
this.file = event.target.files;
this was the error this should be corrected to
this.file = event.target.files[0];