Spring boot octet-stream 不支持在 formdata 中包含图像文件和 JSON 详细信息的 PUT 端点

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

我正在构建一个带有

PUT
端点的 Spring Boot 应用程序,以使用以下代码使用图像文件和一些客户详细信息。

@PutMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<ProfileDetails> updateProfileDetails(@RequestPart("profile_details") UpdateProfileDetailsRequest updateProfileDetailsRequest,
                                                                  @RequestPart("profile_image") MultipartFile profileImage,
                                                                  @PathVariable("id") String profileId){
   
    var updatedProfile = service.updateProfileDetails(new UpdateProfileDetailsRequest(),profileId);
    return ResponseEntity.ok(updatedProfile);
}

现在前端 React 应用程序通过发送

profile_details
profile_image
中的
formData
来使用此 API,如下所示。

profile_details: {"email_id":"[email protected]"}
profile_image: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QBaRXhpZgAATU

我能够在 chrome 检查模式下看到此请求正文,并且它还将内容类型标头作为 formdata 发送

  content-type: multipart/form-data; boundary=----WebKitFormBoundaryYBCGyw8abCFWMGh9

但由于某种原因,应用程序失败并出现以下错误,我找不到有关在同一 api 中使用 JSON 数据和文件的更多信息 😔

[nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/octet-stream' is not supported]
java spring spring-boot
1个回答
0
投票

在进行更多研究时,我发现这篇post对于我们需要从reactjs应用程序发送blob格式的

JSON
IMAGE
很有帮助,但帖子中的答案没有最新的以 blob 格式发送它们的代码。我已经更新了reactjs应用程序中的代码如下

const updatedData = {email_id: '[email protected]'}
const updatedDataBlob = new Blob([JSON.stringify(updatedData)], {
            type: 'application/json'
          });
const imageBlob = new Blob([profileImage], { type: profileImage.type });
formDataBody.append('profile_details', updatedDataBlob);
formDataBody.append('profileImage', imageBlob);

const response = await academyApiAxios.put(`/profiles/${profileId}`, formDataBody, {headers:{'Content-Type':'multipart/form-data'}});
© www.soinside.com 2019 - 2024. All rights reserved.