Can't access image file from src/main/webapp/WEB-INF/resources/img in controller to display in jsp

parsecer :

I try to display images from src/main/webapp/WEB-INF/resources/img/ folder (different from src/main/resources)

@Controller
@RequestMapping("/items")
public class ItemsController {
    @GetMapping( "/images/{itemId}")
    @ResponseBody
    public byte[] getItemImageById(@PathVariable long itemId) throws IOException {
           BufferedImage originalImage =
                ImageIO.read(
            new File("/WEB-INF/resources/img/" + itemId + ".png"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write( originalImage, "png", baos );
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();
        return imageInByte;
    }
}
<img src='${pageContext.request.contextPath}/items/images/1'/>

It doesn't work - no image, but if I replace the path in the File constructor with absolute path like this: C://.../some_file.png it works fine.

Marco Behler :

You cannot go through a "File" to read in your image you need to go through the ServletContext.

@Controller
@RequestMapping("/items")
public class ItemsController {

   @Autowired
   ServletContext context;

    @GetMapping( "/images/{itemId}")
    @ResponseBody
    public byte[] getItemImageById(@PathVariable long itemId) throws IOException {
           BufferedImage originalImage =
                ImageIO.read(context.getResourceAsStream("/WEB-INF/resources/img/" + itemId + ".png"));

        // your original code
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=295473&siteId=1