0

I have one API in which I have to send a response which contains one binary,

I tried some example from StackOverflow but I did not get any solution.

I tried In Jersey

   @POST
    @Path("/testmultipart")
    @Consumes("application/json")
    @Produces("multipart/mixed")
    public Response multipartTest() throws URISyntaxException, MessagingException, IOException 
    {
         File image = new File("C:\\Users\\ganesh\\img\\logo.png");
         MultiPart objMultiPart = new MultiPart();
         objMultiPart.type(new MediaType("multipart", "mixed"));
         objMultiPart.bodyPart(image.getName(), new MediaType("text", "plain"));
         objMultiPart.bodyPart("" + image.length(), new MediaType("text","plain"));
         objMultiPart.bodyPart(image, new MediaType("multipart", "mixed"));
         return Response.ok(objMultiPart).build();
    }

But no luck can you please help.

Ganesh Gudghe
  • 1,327
  • 1
  • 17
  • 41

1 Answers1

1

For sending single file:

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
 public Response multipartTest() {
  File file = new File("C:\\Users\\ganesh\\img\\logo.png");
  return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
      .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) 
      .build();
}

There are couple of alternatives to return zip multi-part response too.

Use below code to send multiple data objects in one go.

MultiValueMap<String, Object> body
  = new LinkedMultiValueMap<>();
body.add("firstName", getFirstName());
body.add("images", getImage1());
body.add("images", getImage2());
body.add("lastName", getLastName());

HttpEntity<MultiValueMap<String, Object>> entityData
  = new HttpEntity<>(body, headers);

RestTemplate template = new RestTemplate();
ResponseEntity<String> response = template
  .postForEntity('endpoinit URL', entityData, String.class);  
Dark Knight
  • 8,218
  • 4
  • 39
  • 58