Server Spring boot无法解析多部分请求

问题描述 投票:0回答:1

遇到内容类型错误

零件正面有一张表格,并附有一个文件 enter image description here

我必须接受前面的请求并处理它。但是当前端发送服务请求时,我们得到一个错误: 已解决 [org.springframework.web.HttpMediaTypeNotSupportedException:不支持 Content-Type 'multipart/form-data;boundary=----WebKitFormBoundaryn1nNr7iOEen0Aykw']

我可能以为服务器不接受请求,但我通过邮递员测试了它,一切正常 enter image description here enter image description here Front 则测试了对 https://httpbin.org/#/HTTP_Methods/post_post 的请求,一切顺利。该服务发出了积极的回应。 enter image description here

这就是 js 文件的样子:

async function submitDataToBackend(data, file, formDataa) {
  const formatedFormData = dataFormattingIntoJSON(data);
  const formData = new FormData();
  formData.append('form', formatedFormData);
  if (file) {
    formData.append('CV', file);
  }

  for (const pair of formData.entries()) {
    console.log('key: ', pair[0], ';       value: ', pair[1]);
  }

  const headers = new Headers();
  headers.append("Content-Type", "multipart/form-data");

  fetch('http://localhost:8081/api/v1/forms/newproject', {
    method: 'POST',
    headers: headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log('response from server: ', data);
      })
      .catch((error) => {
        console.log(error);
      });
}

处理请求的服务器控制器

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/forms")
@Tag(name = "Forms Controller", description = "Forms API")
@Slf4j
public class FormsController {
    private final EmailServiceMarsNet emailServiceMarsNet;

    @PostMapping(value="/newproject",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    @Operation(summary = "Method for send email form 'Start your NEW project'")
    public StartProjectDTO sendStartProjectRequest(@RequestPart(value = "form") @Valid StartProjectDTO request,
                                                   @RequestPart(value = "CV", required = false) MultipartFile file){
        log.info(request.toString());
        emailServiceMarsNet.sendFormStartYourProjectNew(request,file);
        return request;
    }
}

也许我写的控制器不正确?

如果您需要更多信息来了解情况,请写在评论中

java spring-boot multipartform-data content-type
1个回答
0
投票

当您在同一请求中包含 JSON 和文件时,您应该对 JSON(相应的 Java 对象)使用 @RequestParam,对文件使用 @RequestPart。试试这个:

public StartProjectDTO sendStartProjectRequest(
                   @RequestParam(value = "form") @Valid StartProjectDTO request,
                   @RequestPart(value = "CV", required = false) MultipartFile file)
© www.soinside.com 2019 - 2024. All rights reserved.