如何解决使用Spring在REST API中显示图像时黑色背景
我想在进行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());
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。