How can I display image from database in HTML and JSP code? I wrote this code in JSP.
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MindDotEditor posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex, nofollow" />
<link href="../sample.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../fckeditor.gif" type="image/x-icon" />
</head>
<body>
<%
String url = "jdbc:mysql://localhost:3306/sample";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String id = (String) session.getAttribute("id");
int j = Integer.parseInt(id);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url,"root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT Image_File FROM Images WHERE Image_id = '3' ");
int i = 1;
if(rs.next()) {
Blob len1 = rs.getBlob("Image_File");
int len = (int)len1.length();
byte[] b = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index = readImg.read(b, 0, len);
System.out.println("index" +index);
stmt.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(b,0,len);
response.getOutputStream().flush();
}
} catch(Exception ex) {
out.println(ex);
} finally {
rs.close();
stmt.close();
con.close();
}
%>
<br>
<center><input type="button" value="Print" onclick="window.print();return false;" /></center>
</body>
</html>