【问题标题】:How to upload an image using ByteArrayOutputStream in Vaadin?如何在 Vaadin 中使用 ByteArrayOutputStream 上传图像?
【发布时间】:2015-08-13 05:08:41
【问题描述】:

我想以字节数组的形式接收上传的图像(以便可以将其插入到 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);
            }
        }, ""));

    }
});

【问题讨论】:

  • 在getStream()方法中获取字节,看看是否有帮助。
  • 你的意思是字节变量?如果我打印它,它只包含几个字符
  • 是的。 bytes 变量。
  • 如果我打印它只包含几个字符
  • 在 getStream() 方法中使用bytes = baos.toByteArray()

标签: java vaadin vaadin7


【解决方案1】:
image.setSource(new StreamResource(new StreamResource.StreamSource() {
  @Override
  public InputStream getStream() {
    return new ByteArrayInputStream(baos.toByteArray());
  }
}, ""));

【讨论】:

  • 我们希望对您的解决方案做一个简短的解释,而不是“试试这个”,因为解决方案“baos.toByteArray()”已经在 cmets 中了。
【解决方案2】:

您可以尝试将带有一些日志的 ProgressListener 添加到 Upload 以查看发生了什么;您将获得读取字节数和总内容长度作为updateProgress 方法的参数,以便您查看是否正在发送所有内容。

【讨论】:

    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2019-04-18
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多