我希望将上传的图像作为字节数组接收(以便可以将其插入到sql数据库中)。 我还想将上传的图像显示为预览。
我已经尝试了以下代码,但我没有收到完整图像的字节。 (如果我打印字节数组,它只打印几个字符)
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);
}
}, ""));
}
});
答案 0 :(得分:0)
image.setSource(new StreamResource(new StreamResource.StreamSource() {
@Override
public InputStream getStream() {
return new ByteArrayInputStream(baos.toByteArray());
}
}, ""));
答案 1 :(得分:0)
您可以尝试将带有一些日志的ProgressListener添加到Upload上,以查看发生了什么;您将获得读取字节数和总内容长度作为updateProgress
方法的参数,以便查看是否所有内容都已发送。