【问题标题】:How to pass byte[] array from InputStrem to OutputStream?如何将字节 [] 数组从 InputStream 传递到 OutputStream?
【发布时间】:2011-06-22 10:10:45
【问题描述】:

我已将我的image as mediumblob 存储在数据库中

在我的 Image bean 类中,我将照片属性存储为 byte[] 之类的

private byte[] photo;

// getter and setter method for photo

我从数据库中获取图像用于存储在 Image bean 类中

image.setPhoto(resultset.getBinaryStreams(1));

然后我在 Servlet 中得到图像:

InputStream input = null;
OutputStream output = null;
try {
    input = new ByteArrayInputStream(image.getPhoto());

    output = // What type of stream should I use here

    byte[] buffer = new byte[10240];
    int length;
    while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} finally {
    output.flush();
    input.close();
}

问题:

  1. 我应该在输出行写什么以使用 response.getOutputStream 或其他方式显示照片?
  2. 这种方法正确还是有更好的方法?

【问题讨论】:

    标签: java jakarta-ee inputstream outputstream


    【解决方案1】:

    您的output 流可以是response.getOutputStream() 直接返回的流。只需确保在将所有数据写入流后刷新流即可。

    如果您的 servlet 容器没有缓冲输出流,您可以考虑将输出包装在 BufferedOutputStream 中。

    【讨论】:

    • servlet 容器不仅缓存,它还写入 ByteArrayOutputStream,因此它可以计算 Content-Length 标头。您不必自己缓冲。
    • 我已经完成了ServletOutputStream output = response.getOutputStream(); 并得到了NPE Exception at output.flush();
    • 在调用flush()之前你能写吗?
    • 好吧,如果我不得不猜测,我会说input = new ByteArrayInputStream(image.getPhoto()); 行失败了。因为imagenullimage.getPhoto() 返回null。您的finally 块应同时检查inputoutputnull,因为它们位于null 之外try/finally 块。
    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多