java 接口返回图片_SpringBoot使用@ResponseBody返回图片的实现
时间: 2023-08-06 20:06:48 浏览: 51
在SpringBoot中使用@ResponseBody返回图片可以分为以下几个步骤:
1. 在Controller中定义一个请求方法,该方法返回一个byte[]类型的数据,该byte[]数组代表图片的字节流。
```java
@GetMapping("/image")
@ResponseBody
public byte[] getImage() throws IOException {
// 从文件中读取图片字节流
File file = new File("image.jpg");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int)file.length()];
fis.read(data);
fis.close();
return data;
}
```
2. 在JSP或HTML页面中使用img标签引用该请求方法,例如:
```html
<img src="/image" />
```
3. 启动SpringBoot应用程序,访问该页面即可显示图片。
需要注意的是,在使用@ResponseBody返回图片时,需要设置正确的ContentType,例如:
```java
response.setContentType("image/jpeg");
```
完整的代码示例可以参考以下代码:
```java
@RestController
public class ImageController {
@GetMapping("/image")
@ResponseBody
public byte[] getImage() throws IOException {
// 从文件中读取图片字节流
File file = new File("image.jpg");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int)file.length()];
fis.read(data);
fis.close();
return data;
}
}
```
```html
<!DOCTYPE html>
<html>
<head>
<title>SpringBoot返回图片示例</title>
</head>
<body>
<img src="/image" />
</body>
</html>
```