简体   繁体   English

将 MultiPartFile 作为 JSON 请求属性发送到 Spring Boot REST 控制器

[英]Sending MultiPartFile as JSON request Property to Spring Boot REST COntroller

I have a JSON request like below and i want to attach my file ie (pdf,jpeg,png,etc) as part of JSON Request Body Like below.我有一个像下面这样的 JSON 请求,我想附加我的文件,即(pdf、jpeg、png 等)作为 JSON 请求正文的一部分,如下所示。 How would i do that in spring boot REST API.?我将如何在 Spring Boot REST API 中做到这一点。? My request Body is :我的请求正文是:

    {
   "data":{
      "caseCategoryPrefix":"PF",
      "caseNumber":"last name",
      "caseStatusId":1,
      "caseCategoryId":1,
      "caseAttachments":[
         {
            "caseAttachmentId":1,
            "attachmentTypeId":1,
            "createdBy":"abc",
            "file":"" // here i want to attach my file 
         }
      ]
   }
}

As far as I now normal practice to upload file is first upload it, return ID and then save data object.就我现在上传文件的正常做法来说,就是先上传文件,返回ID,然后保存数据对象。

Example 1:示例 1:

To have 2 endpoints in controller.在控制器中有 2 个端点。 One for file upload, second one for data object save.一个用于文件上传,第二个用于数据对象保存。 This method best for bigger files.此方法最适合较大的文件。

@PostMapping(
        value = "/file",
        produces = MediaType.APPLICATION_JSON_VALUE,
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE
)
public String uploadFile(@RequestPart MultipartFile file) {
    // upload file and return generated id;
}

@PostMapping(value = "/data")
public void saveData(@RequestBody Data data) {
    // save data you described. Instead of "file:" save "fileId:"
}

Example 2:示例 2:

To have 1 endpoint and insert file in data object as byte array.具有 1 个端点并将文件作为字节数组插入数据对象中。 This works only with small files.这仅适用于小文件。 Because byte array have some length limitation as far as I know.因为据我所知,字节数组有一些长度限制。

@PostMapping(value = "/data")
public void saveData(@RequestBody Data data) {
    // save data you described with byte[] array in data object
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM