如何使用 Vaadin 上传图片 Java Spring 应用
How can upload image Java Spring app with Vaadin
我想上传一张图片并将其转换为字节[]。现在我可以使用 Vaadin 上传选择图像。但是图片没有上传。
imgU = new Upload();
imgU.setCaption("Upload");
gridLayout.addComponent(imgU);
我该怎么办?
您需要添加一个侦听器,然后处理接收到的文件。
在此处查看更多详细信息和示例:https://vaadin.com/components/vaadin-upload/java-examples
它将看起来像这样:
upload.addSucceededListener(event -> {
Component component = createComponent(event.getMIMEType(),
event.getFileName(), buffer.getInputStream());
showOutput(event.getFileName(), component, output);
});
上传需要 Receiver
才能正常工作。然后您需要提供一个 OutputStream(如 ByteArrayOutputStream),然后在成功的侦听器中您可以从缓冲区中读取字节。我刚刚发布了 a blog entry 更详细地解释了这一点。
对于您的用例,我建议使用 EasyUploads add-on 中的 UploadField 或 ImagePreviewField 组件。使用那些你也可以绑定器,例如,如果你正在将图像数据存储到 JPA 实体,或者只是使用 getValue()
方法来 return 值更改侦听器中的 byte[]。
我想上传一张图片并将其转换为字节[]。现在我可以使用 Vaadin 上传选择图像。但是图片没有上传。
imgU = new Upload();
imgU.setCaption("Upload");
gridLayout.addComponent(imgU);
我该怎么办?
您需要添加一个侦听器,然后处理接收到的文件。
在此处查看更多详细信息和示例:https://vaadin.com/components/vaadin-upload/java-examples
它将看起来像这样:
upload.addSucceededListener(event -> {
Component component = createComponent(event.getMIMEType(),
event.getFileName(), buffer.getInputStream());
showOutput(event.getFileName(), component, output);
});
上传需要 Receiver
才能正常工作。然后您需要提供一个 OutputStream(如 ByteArrayOutputStream),然后在成功的侦听器中您可以从缓冲区中读取字节。我刚刚发布了 a blog entry 更详细地解释了这一点。
对于您的用例,我建议使用 EasyUploads add-on 中的 UploadField 或 ImagePreviewField 组件。使用那些你也可以绑定器,例如,如果你正在将图像数据存储到 JPA 实体,或者只是使用 getValue()
方法来 return 值更改侦听器中的 byte[]。