首页 > 解决方案 > 在 Vaadin 14/RapidclipseX IMG 组件中访问本地资源(本地目录-项目外)

问题描述

如何在图像组件中从我的硬盘驱动器(外部项目文件夹)访问本地图像文件(以制作图像库)?如何写文件的路径?在 Vaadin 14/RapidclipseX 中。

它只需要来自项目或 URL 的路径。在我的项目中,用户必须上传图片,我想制作一个展示图片的画廊。

我尝试了以下所有方法,但没有奏效:

D:\\Canavans\\Reports\\256456\\424599_320943657950832_475095338_n.jpg
D:\Canavans\Reports\256456\424599_320943657950832_475095338_n.jpg

代码(也试过这种方式):

for(final File file: files)
    {
        System.out.println(file.getName());
        this.log.info(file.getName());
        this.log.info(file.getAbsolutePath());
        final String path = "file:\\\\" + file.getAbsolutePath().replace("\\", "\\\\");
        this.log.info(path);
        final Image img = new Image();
        img.setWidth("300px");
        img.setHeight("300px");
        img.setSrc("file:\\\\D:\\\\Canavans\\\\Reports\\\\256456\\\\IMG20171002142508.jpg");
        this.flexLayout.add(img);
    }

请帮忙!提前致谢。或者有没有其他方法可以创建图片库?

标签: vaadin14rapidclipse

解决方案


嗯,据我所知,如果你想访问资源文件夹之外的资源,你可以创建一个 StreamResource 并用它初始化图像。如果您想使用图像“src”属性,则该文件必须位于 Vaadin 的资源文件夹之一中(例如“webapp”文件夹)。

下面是一个关于如何使用 StreamResource 创建图像的简单示例:

final StreamResource imageResource = new StreamResource("MyResourceName", () -> {
    try
    {
        return new FileInputStream(new File("C:\\Users\\Test\\Desktop\\test.png"));
    }
    catch(final FileNotFoundException e)
    {
        e.printStackTrace();
        return null;
    }
});

this.add(new Image(imageResource, "Couldn't load image :("));

希望这可以帮助 :)


推荐阅读