【问题标题】:Can't access image file from src/main/webapp/WEB-INF/resources/img in controller to display in jsp无法从控制器中的 src/main/webapp/WEB-INF/resources/img 访问图像文件以在 jsp 中显示
【发布时间】:2020-03-16 22:31:39
【问题描述】:

我尝试显示来自src/main/webapp/WEB-INF/resources/img/ 文件夹的图像(不同于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'/>

它不起作用 - 没有图像,但如果我用绝对路径替换 File 构造函数中的路径,如下所示:C://.../some_file.png 它工作正常。

【问题讨论】:

    标签: java spring spring-boot spring-mvc jsp


    【解决方案1】:

    您无法通过“文件”读取图像,您需要通过 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
        }
    }
    

    【讨论】:

    • 另外你怎么看另一种方法(第二个答案)?
    【解决方案2】:

    对我有用的另一种方法是:

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

    【讨论】:

    • ResourceLoader 将是一个 ServletContextResourceLoader 并且与您手动执行的操作完全相同:使用 servletcontext 获取资源。至于转换为文件:这将适用于扩展的 war.files ,但不适用于未扩展的文件,这是一个不必要的步骤,因为您可以直接获取 InputStream 而无需通过文件。
    猜你喜欢
    • 2014-03-31
    • 2020-11-01
    • 1970-01-01
    • 2015-06-18
    • 2014-08-17
    • 2012-06-30
    • 1970-01-01
    • 2012-05-06
    • 2017-11-25
    相关资源
    最近更新 更多