简体   繁体   中英

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

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.

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
    }
}

Another approach that worked for me is:

@Autowired
ResourceLoader resourceLoader;

Resource resource =  resourceLoader.getResource(
                "/WEB-INF/resources/img/" + itemId + ".png");
String path = resource.getFile().getPath();
return Files.readAllBytes(Paths.get(path));

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