如何在 Vaadin 中使用 ByteArrayOutputStream 上传图像? [英] How to upload an image using ByteArrayOutputStream in Vaadin?
问题描述
我想以字节数组的形式接收上传的图像(以便它可以插入到 sql 数据库中).我还想将上传的图片显示为预览.
I want to receive an uploaded image as a byte array (so that it can be inserted into a sql database). I also want to show the uploaded image as a preview.
我尝试了以下代码,但我没有收到完整图像的字节.(如果我打印字节数组,它只打印几个字符)
I have tried the following code but im not receiving the bytes of the full image. (if i print the byte array it prints only a few characters)
final Embedded preview = new Embedded("Uploaded Image");
preview.setVisible(false);
final Upload upload = new Upload();
upload.setCaption("Image");
// Create upload stream
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Stream to write to
upload.setReceiver(new Upload.Receiver() {
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
return baos; // Return the output stream to write to
}
});
upload.addSucceededListener(new Upload.SucceededListener() {
@Override
public void uploadSucceeded(Upload.SucceededEvent succeededEvent) {
final byte[] bytes = baos.toByteArray();
preview.setVisible(true);
preview.setSource(new StreamResource(new StreamResource.StreamSource() {
@Override
public InputStream getStream() {
return new ByteArrayInputStream(bytes);
}
}, ""));
}
});
推荐答案
您可以尝试将带有一些日志的 ProgressListener 添加到 Upload 以查看发生了什么;您将获得读取字节数和总内容长度作为 updateProgress
方法的参数,以便您可以查看是否正在发送所有内容.
You could try adding a ProgressListener with some logs to the Upload to see what is happening; you will get the amount of read bytes and total content length as a parameter to the updateProgress
method so you can see if everything is being sent.
这篇关于如何在 Vaadin 中使用 ByteArrayOutputStream 上传图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!