Home > Software engineering >  How to return both JSON response and Byte Array of file in Springboot RestController Response while
How to return both JSON response and Byte Array of file in Springboot RestController Response while

Time:09-06

I am developing a rest controller to download a .docx file into the client system. My code is working fine as the file is getting downloaded. Now I want to enhance the response. My requirement is to also send a JSON payload in the response along with the .docx file content, something like

{"message":"Report downloaded Successfully"}

incase of successful download or with a different message incase of failure.

Below is my restcontroller code:

@RestController
public class DownloadController {
    
    
    @PostMapping(value="/download",
            consumes = {"multipart/form-data"},
            produces = {"application/octet-stream"})
    public ResponseEntity<?> downloadFile(@RequestParam("file") MultipartFile uploadFile){
        
        //business logic to create the attachment file
        
        try {
            
            File file = new File("path_to_.DOCX file_I_have_created");
            byte[] contents = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDisposition(ContentDisposition.attachment().filename("survey.docx").build());
            
            return new ResponseEntity<>(contents, headers, HttpStatus.OK);
        } catch (Exception e){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}

How do I modify my response code to send both the JSON message and the byte[] contents so that the file gets downloaded and I can see the JSON message in the response preview tab in the chrome or response body in postman?

CodePudding user response:

You can't. HTTP doesn't allow you to defined multiple content-types on 1 request/response. That being said, you could send the byte array base64 encoded as part of a json response but would need to handle it in the front-end (if you have any) as it would not trigger the file download process of the browser.

CodePudding user response:

You can define custom class which hold your current content and message . So you can return that class in the response

ResponseClass
{
byte[] contents;
String message;
}
  • Related