簡體   English   中英

下載文件時如何在Springboot RestController響應中同時返回JSON響應和文件字節數組

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

我正在開發 rest controller 以將 a.docx 文件下載到客戶端系統中。 隨着文件的下載,我的代碼運行良好。 現在我想增強響應。 我的要求是在響應中還發送一個 JSON 有效負載以及 .docx 文件內容,例如

{"message":"Report downloaded Successfully"}

下載成功或失敗時顯示不同的消息。

下面是我的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);
        }
    }

}

如何修改我的響應代碼以同時發送 JSON 消息和 byte[] 內容,以便下載文件,並且我可以在 Z03D4762CB861AFD38141ZCCF 的 chrome 或響應正文中的響應預覽選項卡中看到 JSON 消息?

你不能。 HTTP 不允許您在 1 個請求/響應中定義多個內容類型。 話雖如此,您可以發送字節數組 base64 作為 json 響應的一部分編碼,但需要在前端(如果有的話)處理它,因為它不會觸發瀏覽器的文件下載過程。

您可以定義自定義 class 來保存您當前的內容和消息。 所以你可以在響應中返回 class

ResponseClass
{
byte[] contents;
String message;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM