JSP:上传图片到数据库并从数据库调用图片

1主界面,上传图片界面

<%@ page contentType="text/html;charset=gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head></head>
<body>
<form name="form1" method="post" action="testimage.jsp">
  <p align="center">请选择图片的URL:
    <input type="file" name="image">
</p>
  <p align="center">
    <input type="submit" name="Submit" value="提交">
</p>
</form>
</body>
</html>

2连接服务器,传入图片信息

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*" %> 
<%@ page import="java.util.*"%> 
<%@ page import="java.text.*"%> 
<%@ page import="java.io.*"%>
<%@ page import="java.nio.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
    <body>
     <%
        Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        //加载JDBC驱动程序   
        String  url="jdbc:mysql:"
				+ "//127.0.0.1:3306/bin_db?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT"; 
       //bin_db为你的数据库的名称   
        String  user="root";    
        String  password="123456";       //密码为自己数据库的密码   
      
        String filename=request.getParameter("image");
         File file = new File(filename); //获取表单传过来的图片的url           
        try {
			//打开文件
			FileInputStream fin = new FileInputStream(file);
			//建一个缓冲保存数据
			ByteBuffer nbf = ByteBuffer.allocate((int) file.length());
			byte[] array = new byte[1024];
			int offset = 0, length = 0;
			//读存数据
			while ((length = fin.read(array)) > 0) {
				if (length != 1024)
					nbf.put(array, 0, length);
				else
					nbf.put(array);
				offset += length;
			}
		  //新建一个数组保存要写的内容
			byte[] content = nbf.array();
			//创建数据库连接
			Connection  conn=  DriverManager.getConnection(url,user,password);
			//保存数据
			Statement stmt =conn.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_UPDATABLE);
			String sqlstr = "select * from bindata where filename='01'";
			ResultSet rs = stmt.executeQuery(sqlstr);
			if (rs.next()) 
			{
				rs.updateBytes(2, content);
				rs.updateRow();
			} else {
				rs.moveToInsertRow();
				rs.updateString(1, "01");
				rs.updateBytes(2, content);
				rs.insertRow();
			}
			rs.close();
//			关闭文件
			fin.close();
			out.println("恭喜,已经将新的记录成功地添加到数据库中!");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}		
   %> 
    </body>
</html>

3从数据库中调用图片

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="java.io.*"%>
<html>
<body>
	<%
		Class.forName("com.mysql.cj.jdbc.Driver");
		//加载JDBC驱动程序   
		String url = "jdbc:mysql:"
				+ "//127.0.0.1:3306/bin_db?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";
		//bin_db为你的数据库的名称   
		String user = "root";
		String password = "123456";
		Connection conn = DriverManager.getConnection(url, user, password);
		//创建数据库连接
		String sql = "select binfile from bindata where filename='01'"; //查询filename为01的记录的pic字段
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
		}
		try {
			while (rs.next()) {
				response.setContentType("image/jpeg"); //设置返回图像的类型
				ServletOutputStream sout = response.getOutputStream();
				//声明ServletOutputStream的实例sout
				InputStream in = rs.getBinaryStream(1); //获取二进制输入流
				byte b[] = new byte[0x7a120];// 创建byte数组用作缓冲
				for (int i = in.read(b); i != -1;) {
					sout.write(b); //向输出流中写入返回页面的内容 
					in.read(b); //读取输入流中的数据 
				}
				sout.flush();
				sout.close(); //关闭输入流
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	%>
</body>
</html>

数据库代码:


create database bin_db;
use bin_db;
create table bindata(
filename char(255) not null,
binfile longblob,
primary key (filename)
);

猜你喜欢

转载自blog.csdn.net/qq_42192693/article/details/81325436