0

I have a JSON request like below and i want to attach my file i-e (pdf,jpeg,png,etc) as part of JSON Request Body Like below. How would i do that in 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 
         }
      ]
   }
}
Tariq Abbas
  • 121
  • 1
  • 13

1 Answers1

0

As far as I now normal practice to upload file is first upload it, return ID and then save data object.

Example 1:

To have 2 endpoints in controller. 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:

To have 1 endpoint and insert file in data object as byte array. 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
}
Dumbo
  • 1,630
  • 18
  • 33
  • Thank you for your answer ,Dumbo, the solution is valid but i have a different scenario where i have to relate attachment to its unique id and its type in database. like when i save json object in database i need to save "caseAttachments" object which is having attachment information along with its url where it is saved . – Tariq Abbas Oct 27 '20 at 07:20
  • hi @TariqAbbas Did u get a solution for this? – Amol Kshirsagar May 11 '22 at 01:33