在java中实现图片的上传,并且显示图片到页面的功能分为以下几步:
1、上传图片代码(此处是读取图片,转换为流,写入数据库中保存)
FileInputStream fis = new FileInputStream("d:/test/2.jpg");
//此处是mysql数据库驱动
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://192.168.67.19/xkxtbeta";
//配置链接字符串,用户名和密码
Connection connection = DriverManager.getConnection(url, "root", "123");
//sql语句的生成采用参数注入的方式,且img字段的类型是BLOB类型
String sql = "insert into image (id,img) values(?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, 2);
statement.setBinaryStream(2, fis);
statement.execute();
connection.close();
2、从数据库中读取图片的二进制流,写入response中,代码如下:
@RequestMapping(value = "showimg.do", method = RequestMethod.GET)
public void showImg(HttpServletRequest request,
HttpServletResponse response, ModelMap map) throws Exception {
Integer id = Integer.valueOf(request.getParameter("id"));
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://192.168.67.19/xkxtbeta";
Connection conn = DriverManager.getConnection(url, "root", "typ");
String sql = "select img from image where id="+id;
Statement sm = conn.createStatement();
ResultSet rs = sm.executeQuery(sql);
byte[] b = null;
if (rs.next()) {
b = rs.getBytes(1);
}
OutputStream os = response.getOutputStream();
os.write(b);
conn.close();
}
3、jsp页面代码,在jsp页面上面输出
此处是img的src访问第二步定义的showimg.do即可
<!DOCTYPE html>
<html>
<head>
<script src="resources/js/jquery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div>
<input type="text"/>
<img src="showimg.do?id=1"></img>
<img src="showimg.do?id=2" style="width:60px;height:60px"></img>
<input type="button" value="submit" />
</div>
</body>
</html>
该程序的结果就是根据jsp传回的id值,显示数据库中存储的两张不同的照片到jsp页面上。