基于Java+JSP+MySQL将数据库的图片读取出来
紧接着上一篇文章将图片存入数据库,这次把图片读取出来。
数据库设计
USE picture;
CREATE TABLE imgs(
id int(11) NOT NULL AUTO_INCREMENT,
img longblob NOT NULL ,
PRIMARY KEY (id)
)DEFAULT CHARSET=utf8;
jsp设计
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<style>
td{
background-color: aquamarine;
width: 200px;
}
</style>
<body>
<center>
<form name="form1" method="post">
<table border="1" bgcolor="aqua">
<tr><td>图片编号:</td><td><input type="text" name="id" value=""/></td></tr>
<tr><td><input type="submit" name="sub" value="展示"/></td>
<td><input type="reset" name="re" value="取消"/></td></tr>
</table>
</form>
</center>
<%
String id = request.getParameter("id");
OutputStream outputStream=null;
String picture=null;
if(id!=null){
Class.forName("com.mysql.jdbc.Driver");
//加载JDBC驱动程序
String url = "jdbc:mysql://localhost:3306/picture";
//picture为数据库的名称
String user = "root";
//连接Mysql数据库的密码
String password = "123456";
Connection connection = null;
try {
connection = DriverManager.getConnection(url,user,password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//数据库连接
String sql = "select * from imgs where id = '"+id+"'";
//根基id查询
Statement statement = null;
ResultSet resultSet = null;
try{
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
}catch (SQLException e){
e.getStackTrace();
}
try {
if(resultSet.next()){
id = resultSet.getString(1);
response.setContentType("image/png");
Blob blob=resultSet.getBlob("img");
long size=blob.length();
byte[] bytes=blob.getBytes(1,(int)size);
outputStream=response.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
picture=bytes.toString();
%>
<center><div id="bg"><img src="<%=picture+"/"+id%>" alt=" "></div></center>
<%
}
else {
out.println(id+"文件不存在");
}
}
catch (Exception e){
System.out.println(e);
}
resultSet.close();
statement.close();
}
%>
</body>
</html>
效果展示