JSP:上传图片到数据库并从数据库调用图片
实现将图片放入数据库,并从数据库调用图片准备:tomcat-9.0.01jdk9eclipse-idemysql8.0mysql-connector-java-8.0.11.jar(jdbc驱动包)一个图片1,建库/建表create database bin_db;//建库use bin_db;create...
·
配置:IDEA2020.2.4、Tomcat9.0.41、mysql5.6、mysql-connector-java5.1
1,创建数据库和数据表
create database pic_database; use pic_database; CREATE TABLE `bindata` ( `fileId` int(11) NOT NULL AUTO_INCREMENT, `fileName` char(255) NOT NULL, `binFile` longblob, PRIMARY KEY (`fileId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2,配置项目
3,创建页面(视图层)
![]()
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form name="form1" method="post" action="upload" enctype="multipart/form-data"> <input type="file" name="file"> <p> <input type="submit" name="Submit" value="提交"> </p> </form> </body> </html>
3,创建Servlet(控制层)
package Controller; import Dao.dao; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; import java.io.*; import java.nio.ByteBuffer; @WebServlet(name = "upload",urlPatterns = {"/upload"}) @MultipartConfig public class upload extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html;charset=UTF-8"); req.setCharacterEncoding("UTF-8"); PrintWriter out = res.getWriter(); //获取上传文件 Part part = req.getPart("file"); //获取包含文件名的字符串 String fileNameInfo = part.getHeader("content-disposition"); //提取上传文件的原始文件名 String fileName = fileNameInfo.substring(fileNameInfo.indexOf("filename=\"")+10,fileNameInfo.length()-1); //打开文件 FileInputStream fin = (FileInputStream) part.getInputStream(); //建一个缓冲保存数据 ByteBuffer nbf = ByteBuffer.allocate((int) part.getSize()); 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(); dao insertDao = new dao("com.mysql.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/pic_database","root","123456"); String sql = "insert into bindata(fileName,binFile) values(?,?)"; try { insertDao.insert(sql,fileName,content); } catch (Exception e) { e.printStackTrace(); } out.print("上传成功!"); } }
4,创建JavaBean(数据访问层)
package Dao; import java.sql.*; public class dao { private Connection connection; private String driver; private String url; private String username; private String password; public dao() { } public dao(String driver, String url, String username, String password) { this.driver = driver; this.url = url; this.username = username; this.password = password; } public Connection getConnection() throws Exception { if(connection == null){ Class.forName(this.driver); connection = DriverManager.getConnection(url,username,password); } return connection; } public boolean insert(String sql,Object... args) throws Exception{ PreparedStatement statement = getConnection().prepareStatement(sql); for (int i=0;i< args.length;i++){ statement.setObject(i+1,args[i]); } if (statement.executeUpdate()!=1){ return false; } return true; } public ResultSet query(String sql,Object... args) throws Exception{ PreparedStatement statement = getConnection().prepareStatement(sql); for (int i=0;i< args.length;i++){ statement.setObject(i+1,args[i]); } return statement.executeQuery(); } public void closeConn() throws Exception{ if (connection!=null&&!connection.isClosed()){ connection.close(); } } public void setConnection(Connection connection) { this.connection = connection; } public String getDirver() { return driver; } public void setDirver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
5,从数据库调用图片
<%@page import="java.io.*"%> <%@page import="java.sql.*"%> <%@ page language="java" contentType="text/html; charset=GB2312" pageEncoding="GB2312"%> <!DOCTYPE html> <html> <head> <meta charset="GB2312"> <title>Insert title here</title> </head> <body> <% try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql:" + "//127.0.0.1:3306/bin_db?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT", "root", "123456"); String sql = "select binfile from bindata where filename='01'"; out.clearBuffer(); out = pageContext.pushBody(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { response.setContentType("image/jpeg"); Blob b = rs.getBlob("binfile"); long size = b.length(); byte bs[] = b.getBytes(1, (int) size); OutputStream outs = response.getOutputStream(); outs.write(bs); outs.flush(); rs.close(); } } catch (Exception e) { e.printStackTrace(); } %> </body> </html>
更多推荐
所有评论(0)