springboot访问图片
时间: 2023-07-03 16:27:57 浏览: 173
在Spring Boot中,你可以使用以下步骤来访问图片:
1. 在你的Controller中添加一个用于返回图片的请求处理器,例如:
```
@GetMapping("/image/{imageName}")
public ResponseEntity<byte[]> getImage(@PathVariable String imageName) throws IOException {
// 读取图片文件
File imageFile = new File(uploadDir, imageName);
byte[] imageBytes = FileUtils.readFileToByteArray(imageFile);
// 构建响应实体并返回
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentLength(imageBytes.length);
return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
}
```
2. 在前端页面中使用img标签来显示图片,例如:
```
<img src="/image/{imageName}" />
```
在这个例子中,{imageName}是你想要访问的图片名称,它将被传递到getImage()方法中,该方法将读取该文件并将其作为字节数组返回。接下来,响应实体将被构建并包含图像的Content-Type和Content-Length头,然后将其作为响应返回。
注意:你需要确保图片文件存在于指定的目录中,并且在访问图片时不会出现访问权限问题。
阅读全文
相关推荐


















