以最佳性能将映像写入servlet响应 [英] Writing image to servlet response with best performance

查看:92
本文介绍了以最佳性能将映像写入servlet响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以最佳性能向servlet响应编写图像。任何建议,做法,经验?

I'm writing an image to servlet response with best performance. Any advices, practices, experience?

推荐答案

为了获得最佳性能和效率,请不要将整个内容放在<$ c $中C>字节[] 。每个字节从Java的内存中吃掉一个字节。想象其请求每个100KB的10张图像100个并发用户,这是已经Java内存的100MB腐蚀掉。

For best performance and efficiency, don't put the entire content in byte[]. Each byte eats, yes, one byte from Java's memory. Imagine 100 concurrent users which requests 10 images of each 100KB, that's already 100MB of Java memory eaten away.

获取的图像作为的InputStream 使用 ResultSet#getBinaryStream(),将其包装在 BufferedInputStream 中,并将其写入在的OutputStream 包裹在一个的BufferedOutputStream 通过小字节[] buffer。

Get the image as an InputStream from the DB using ResultSet#getBinaryStream(), wrap it in an BufferedInputStream and write it to the OutputStream of the response wrapped in an BufferedOutputStream through a small byte[] buffer.

假设您按数据库键选择图像作为标识符,请在HTML中使用:

Assuming that you select images by the database key as identifier, use this in your HTML:

<img src="images/123">

创建一个映射到的 Servlet web.xml url-pattern / images / * 并按如下方式实现其 doGet()方法。:

Create a Servlet class which is mapped in web.xml on an url-pattern of /images/* and implement its doGet() method as follows.:

Long imageId = Long.valueOf(request.getPathInfo().substring(1)); // 123
Image image = imageDAO.find(imageId); // Get Image from DB.
// Image class is just a Javabean with the following properties:
// private String filename;
// private Long length;
// private InputStream content;

response.setHeader("Content-Type", getServletContext().getMimeType(image.getFilename()));
response.setHeader("Content-Length", String.valueOf(image.getLength()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getFilename() + "\"");

BufferedInputStream input = null;
BufferedOutputStream output = null;

try {
    input = new BufferedInputStream(image.getContent());
    output = new BufferedOutputStream(response.getOutputStream());
    byte[] buffer = new byte[8192];
    for (int length = 0; (length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} finally {
    if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
    if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}

ImageDAO#find()您可以使用 ResultSet#getBinaryStream() 将图像作为 InputStream 来自数据库。

In the ImageDAO#find() you can use ResultSet#getBinaryStream() to get the image as an InputStream from the database.

这篇关于以最佳性能将映像写入servlet响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆