问题
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