首页 > 解决方案 > 使用 Vaadin 14 显示的图像

问题描述

我写这篇文章是因为我需要一些帮助。我无法根据我的应用程序中的特定路径显示图像。

基本上它在做什么:我有一个名为 Sector 的模块,每个 Sector 都可以有一个与之相关的图像。当我使用 Vaadin 的 Upload 组件时,我将图像的路径保存到我的数据库中的一个表中,以便它可以显示之前选择的图片。

图像的实际路径很奇怪,似乎 Vaadin 将图像复制到动态随机文件夹中。它不能使用图像的实际路径似乎是合乎逻辑的。

但问题是:在数据库中输入了正确的路径,但是当我重新加载页面(F5)时,Vaadin 无法再显示图像。这让我很不安,因为它应该很好地展示它。

Vaadin 使用上传的图片创建的路径:VAADIN/dynamic/resource/2/c1ef7b9d-8f2b-4354-a97e-fe1fd4e868e7/551434.jpg

如果有帮助,我可以放一些代码。

屏幕截图显示了我刷新浏览器页面后它在做什么。

图片正在上传

刷新页面后

这是我处理上传图片的代码部分:

upload.addSucceededListener(e -> {
            Component component = createComponent(e.getMIMEType(),
                    e.getFileName(), buffer.getInputStream());
            showOutput(e.getFileName(), component, output);
            //imgUpload = (Image) component;
            InputStream inputStream = buffer.getInputStream();
            targetFile = new File(PATH + currentProjetId + "\\secteur" + currentSecId + "\\photoSec.png");
            try {
                FileUtils.copyInputStreamToFile(inputStream, targetFile);
            } catch (IOException e1) {
                e1.printStackTrace();
                Notification.show("Error");
            }
            System.out.println("PATH : " + targetFile.getPath());
        });

标签: javaimageuploadvaadinvaadin14

解决方案


我认为您正在使用刷新视图时丢弃的内存资源。您必须获取文件的内容并将其保存在服务器文件系统目录内的文件中。这是一个例子:

FileBuffer receiver = new FileBuffer();
Upload upload = new Upload(receiver);
upload.setAcceptedFileTypes("text/plain");
upload.addSucceededListener(event -> {
    try {
      InputStream in = receiver.getInputStream();
      File tempFile = receiver.getFileData().getFile();
      File destFile = new File("/some/directory/" + event.getFileName());
      FileUtils.moveFile(tempFile, destFile);
      
    } catch (IOException e) {
      e.printStackTrace();
      Notification.show("Error").
    }
});

推荐阅读