如何使用 java servlet 从 mysql 数据库中检索图像并将其显示在 HTML img 标记中?还有那个 ima 标记应该放在表定义中吗?
问问题
15160 次
2 回答
2
编写一个 servlet,将其映射到类似的 url showImage.html
,将图像名作为参数传递
<img src="showImage.html?filename=new.jpg">
然后从文件中读取 byte[] 并写入 servlet 代码中的响应 OutputStream。
response.getOutputStream().write(bytes);
从文件中获取字节 []
RandomAccessFile f = new RandomAccessFile("c:\images\pic1.png", "r");
byte[] bytes = new byte[(int)f.length()];
f.read(bytes);
response.getOutputStream().write(bytes);
于 2013-01-29T13:02:27.587 回答
0
类似于下面的代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException {
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ServletOutputStream out = response.getOutputStream();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.0:3306/
example","root","root"); // localhost:<defaultport>
stmt = con.createStatement();
rs = stmt.executeQuery("select image from pictures where id = '2'");
if (rs.next()) {
image = rs.getBlob(1);
} else {
response.setContentType("text/html");
out.println("<font color='red'>image not found for given id</font>");
return;
}
response.setContentType("image/gif");
InputStream in = image.getBinaryStream();
int length = (int) image.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
} catch (Exception e) {
response.setContentType("text/html");
out.println("<html><head><title>Unable To Display image</title></head>");
out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() +
"</font></h4></body></html>");
return;
} finally {
try {
rs.close();
stmt.close();
con.close();
}
于 2013-01-29T12:57:28.190 回答