How to upload an image using ByteArrayOutputStream in Vaadin?

眉间皱痕 提交于 2020-01-07 05:58:06

问题


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);
            }
        }, ""));

    }
});

回答1:


image.setSource(new StreamResource(new StreamResource.StreamSource() {
  @Override
  public InputStream getStream() {
    return new ByteArrayInputStream(baos.toByteArray());
  }
}, ""));



回答2:


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.



来源:https://stackoverflow.com/questions/31979896/how-to-upload-an-image-using-bytearrayoutputstream-in-vaadin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!