0
votes

I am trying to parse the MultipartFile data to string and return the string as response in java springboot. Can anyone suggest the right approach for this?

controller.java

@POST
@Path("/modelInfo")
@Produces({ "application/json" })
public Response getPretrainedModel(MultipartFile data) throws IOException {
    String content = new String(data.getBytes(), StandardCharsets.UTF_8);
    return Response.status(Response.Status.OK).entity(content).build();
}

file.json

{
  "documents": [
    {
      "id": "1",
      "text": "abc"
    }
  ]
}

I am sending file.json in request body as multipart/form-data and I want to read the content of the file and store it as string.

1

1 Answers

0
votes

If you are using Spring and Spring Boot, then you are not using the proper annotation. Spring does not support Jax-RS specification. Therefor, change your annotations for this one:

//    @POST
//    @Path("/modelInfo")
//    @Produces({ "application/json" })
@PostMapping(value = "/modelInfo", produces = MediaType.APPLICATION_JSON_VALUE)

Then, to return an object, you can just return the object in the method:

@PostMapping(value = "/modelInfo", produces = MediaType.APPLICATION_JSON_VALUE)
public String getPretrainedModel(@RequestParam("file") MultipartFile data) throws IOException {
    String content = new String(data.getBytes(), StandardCharsets.UTF_8);
    return content;
}

Note:

  • Don't forget to add the annotation @RequestParam in your method parameter to get the uploaded file. The name file must be the name of the attribute uploaded by your POST request
  • By default, the HTTP Response is 200 when you don't tell Spring to send something else.
  • If you want to override that, annotate your method with @ResponseStatus