发送表单数据类型请求时出现 400 HTTP 错误

时间:2021-02-16 06:13:19

标签: angular spring-boot rest spring-security multipartform-data

大家好,我正在从(angular CLI 11)前端向(spring boot)后端发送表单数据类型请求。在此请求中,我想发送包含一些详细信息的图像。
无论如何,当我发送请求时出现 400 错误

  • 前端服务类相关方法
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'
    });
  }
  • 后端相关的post方法
@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);
        }
    }
  • CORS 过滤器
@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);
    }
}

1 个答案:

答案 0 :(得分:0)

好的,我终于找到了答案。问题是我创建表单数据体时发生的错误:/在那里我为文件元素设置了错误的值。在 component.ts 中,

$('#my-dropdown-id option:selected')

这是应该纠正的错误

this.file = event.target.files;
相关问题