问题描述
我想在进行GET
请求时返回指向图像(或图像本身)的链接。我看了Baeldung的教程,并决定使用它。代码如下:
@RequestMapping(value = "/image-manual-response",method = RequestMethod.GET)
public void getImageAsByteArray(HttpServletResponse response) throws IOException {
InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in,response.getOutputStream());
}
由于我无法弄清楚servletContext
是什么并且找不到我需要的信息,因此我对方法进行了少许更改:
@GetMapping("/image")
public void getImageAsByteArray(HttpServletResponse response) throws IOException {
InputStream in = new ByteArrayInputStream(("C:\\Users\\vartanyan\\Desktop\\images\\Puer").getBytes());
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in,response.getOutputStream());
}
结果,在Swagger中,我得到了以下内容:
如何解决此问题?我正在使用Rest
,MVC
,Spring Boot
来编写Hibernate
PostgreSQL
应用。
解决方法
从请求中获取servletContext,如下所示:
@GetMapping("/image")
public void getImageAsByteArray(HttpServletRequest request,HttpServletResponse response) throws IOException {
InputStream in = request.getServletContext().getResourceAsStream("images/Puer.jpg");
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in,response.getOutputStream());
}
,
尝试以下代码:
@GetMapping("/image")
public void getImageAsByteArray(HttpServletRequest request,HttpServletResponse response) throws IOException {
InputStream in = request.getServletContext().getResourceAsStream("C:\\Users\\vartanyan\\Desktop\\images\\Puer");
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in,response.getOutputStream());
}
,
我添加了FileInputStream()
实现。例如:
public void getDrinkImage(HttpServletResponse response,Long drinkId) throws IOException {
String imageURL = drinkRepository.getById(drinkId).getImage();
InputStream in = new FileInputStream(uploadPath + imageURL);
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in,response.getOutputStream());
}