[英]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.