簡體   English   中英

在 Spring Boot 中動態設置 Content-Type header

[英]Set the Content-Type header dynamically in Spring Boot

我有一個 controller 方法,它提供從 Base64 字符串解碼的文件。

// Simplified from original
@GetMapping("/download/{id}")
public byte[] download(@PathVariable String id, HttpServletResponse response) throws Exception {
    var doc = new Document("test.pdf", "application/pdf", "Base64 encoded data"); // This is loaded from elsewhere

    response.addHeader("Content-Type", doc.getType());
    response.addHeader("Content-Disposition", "attachment; filename=\"%s\"".formatted(doc.getFilename()));

    return Base64.getDecoder().decode(doc.getData());
}

當我通過HttpServletResponse設置 header 時, Spring 似乎總是將其覆蓋為text/html 我無法使用注釋或配置對其進行設置,因為我需要在 controller 方法中動態設置它。

如何在不覆蓋 Spring 的情況下動態設置 Content-Type header?

使用ResponseEntity作為返回類型,而不是操縱Response 代碼如下所示:

@GetMapping("/download/{id}")
public ResponseEntity<byte[]> download(@PathVariable String id) throws Exception {
    var doc = new Document("test.pdf", "application/pdf", "Base64 encoded data");

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", doc.getType());
    headers.add("Content-Disposition", "attachment; filename=\"%s\"".formatted(doc.getFilename()));

    return ResponseEntity
        .status(HttpStatus.OK)
        .headers(headers)
        .body(Base64.getDecoder().decode(doc.getData()));
}

您還可以簡化標題的設置。 而不是使用標題名稱

    headers.add("Content-Type", doc.getType());

你可以使用方法

    headers.setContentType(doc.getType());

暫無
暫無

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

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