java—使用spring在RESTAPI中显示图像时的黑色背景

f0ofjuux  于 2021-07-05  发布在  Java
关注(0)|答案(3)|浏览(333)

我想返回一个链接的形象(或形象本身)时,作出了一个决定 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 .

ecfdbz9o

ecfdbz9o1#

请尝试以下代码:

@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());
    }
ao218c7q

ao218c7q2#

从请求中获取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());
}
pw136qt2

pw136qt23#

我补充说 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());
    }

相关问题