0

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

    }
});
tharinduwijewardane
  • 2,593
  • 2
  • 16
  • 28

2 Answers2

0
image.setSource(new StreamResource(new StreamResource.StreamSource() {
  @Override
  public InputStream getStream() {
    return new ByteArrayInputStream(baos.toByteArray());
  }
}, ""));
David Guyon
  • 2,759
  • 1
  • 28
  • 40
  • Instead of "try this" we would prefer a short explaination of your solution because the solution "baos.toByteArray()" was already in the comments. – David Guyon Mar 02 '16 at 14:51
0

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.

ollitietavainen
  • 3,900
  • 13
  • 30