[英]How do I write a Spring Controller method that returns an image?
我想寫一個 Spring controller 方法,它從存儲中返回圖像。 以下是我當前的版本,但它有兩個問題:
請告知如何編寫更通用的 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.