簡體   English   中英

如何編寫返回圖像的 Spring Controller 方法?

[英]How do I write a Spring Controller method that returns an image?

我想寫一個 Spring controller 方法,它從存儲中返回圖像。 以下是我當前的版本,但它有兩個問題:

  1. @GetMapping 注解需要 'produces' 參數,它是一個媒體類型的字符串數組。 如果該參數不存在,程序將無法運行; 它只是將圖像數據顯示為文本。 問題是,如果我想支持其他媒體類型,那么我必須重新編譯程序。 有沒有辦法從 viewImg 方法中設置“生產”媒體類型?
  2. 下面的代碼將顯示除 svg 之外的任何圖像類型,它只會顯示消息“圖像無法顯示,因為它包含錯誤”。 web 瀏覽器 (Firefox) 將其識別為媒體類型“webp”。 但是,如果我從“produces”字符串數組中刪除除“image/svg+xml”條目之外的所有媒體類型,則會顯示圖像。

請告知如何編寫更通用的 controller 方法(以便它適用於任何媒體類型)並且對 svg 媒體類型沒有問題。

這是我的測試代碼:

@GetMapping(value = "/pic/{id}",
        produces = {
                "image/bmp",
                "image/gif",
                "image/jpeg",
                "image/png",
                "image/svg+xml",
                "image/tiff",
                "image/webp"
        }
)
public @ResponseBody
byte[] viewImg(@PathVariable Long id) {

    byte[] data = new byte[0];
    String inputFile = "/path/to/image.svg";
    try {
        InputStream inputStream = new FileInputStream(inputFile);
        long fileSize = new File(inputFile).length();
        data = new byte[(int) fileSize];
        inputStream.read(data);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return data;
}

我推薦FileSystemResource來處理文件內容。 如果您不想發送Content-Type值,可以避免使用.contentType(..)開始行。

@GetMapping("/pic/{id}")
public ResponseEntity<Resource> viewImg(@PathVariable Long id) throws IOException {
    String inputFile = "/path/to/image.svg";
    Path path = new File(inputFile).toPath();
    FileSystemResource resource = new FileSystemResource(path);
    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(Files.probeContentType(path)))
            .body(resource);
}

暫無
暫無

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

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