简体   繁体   English

下载文件时如何在Springboot RestController响应中同时返回JSON响应和文件字节数组

[英]How to return both JSON response and Byte Array of file in Springboot RestController Response while downloading a file

I am developing a rest controller to download a.docx file into the client system.我正在开发 rest controller 以将 a.docx 文件下载到客户端系统中。 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我的要求是在响应中还发送一个 JSON 有效负载以及 .docx 文件内容,例如

{"message":"Report downloaded Successfully"}

incase of successful download or with a different message incase of failure.下载成功或失败时显示不同的消息。

Below is my restcontroller code:下面是我的restcontroller代码:

@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?如何修改我的响应代码以同时发送 JSON 消息和 byte[] 内容,以便下载文件,并且我可以在 Z03D4762CB861AFD38141ZCCF 的 chrome 或响应正文中的响应预览选项卡中看到 JSON 消息?

You can't.你不能。 HTTP doesn't allow you to defined multiple content-types on 1 request/response. HTTP 不允许您在 1 个请求/响应中定义多个内容类型。 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.话虽如此,您可以发送字节数组 base64 作为 json 响应的一部分编码,但需要在前端(如果有的话)处理它,因为它不会触发浏览器的文件下载过程。

You can define custom class which hold your current content and message.您可以定义自定义 class 来保存您当前的内容和消息。 So you can return that class in the response所以你可以在响应中返回 class

ResponseClass
{
byte[] contents;
String message;
}

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

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