简体   繁体   中英

Black background when display an image in a REST API with Spring

I want to return a link to the image (or the image itself) when making a GET -request. I saw the tutorial from Baeldung and decided to use it. The code looks like this:

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

Since I could not figure out what servletContext is and find the information I needed, I slightly changed the method:

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

As a result, in Swagger I got the following:

在此处输入图片说明

And when I open the image in a separate window, I get the following: 在此处输入图片说明

How can this problem be corrected? I am writing Rest MVC app using Spring Boot , Hibernate , PostgreSQL .

Get the servletContext from the request, like this:

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

Try this code:

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

I add FileInputStream() realisation. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM