上传图片至数据库及从数据库中读取图片显示至页面
Posted linkinsj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传图片至数据库及从数据库中读取图片显示至页面相关的知识,希望对你有一定的参考价值。
1.基于最简单的servlet+jsp+jdbc实现
2.实验环境:myeclipse以及tomcat 8.5
3.所需jar包:
4.数据库:
数据库用的是mysql 5.6.37
其中imag字段是MediumBlob(binary large object)类型,其中TinyBlob 最大 255B,Blob 最大 64KB,MediumBlob 最大16MB,LongBlob 最大 4GB
5.先上实验结果:
主页:
提交之后:这个是之前测试用的页面,没改,问题不大,图片插进数据就行了
数据库:成功插进去了
然后读取这张图片(因为在插入的时候设置id都是等于9,所有插入成功之后我改了下这张图的id=8
然后在getSqlImgFile()方法里面的SQL语句改成了String sql = "select imag from image where id = 8";问题不大就是
6.实验代码:
index.jsp选择文件页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <form id="form5" method="post" enctype="multipart/form-data" action="uploadFile"> <input type="file" text" value="浏览" readonly="readonly" name="imgFile"> <a href="testSqlImage.jsp">测试sql图片</a> <input type="submit" value="提交""> </form> </body> </html>
UploadFile.java -- > servlet 使用doPost方法,需要配置web.xml文件如果servlet使用了注解可以不用配置web.xml
具体可以参照文档:http://commons.apache.org/proper/commons-fileupload/using.html
package upload; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import sqlImgUtil.SqlImage; /** * 将图片上传至数据库 * * @author SJ676 * */ public class UploadFile extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String serverPath = getServletContext().getRealPath("/").replace("\\", "/"); // 基于磁盘文件创建工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); // 最大缓存,超过这个阈值将先保存至临时文件目录
factory.setSizeThreshold(10 * 1024);
// 临时文件目录 测试时可以直接打印在控制台显示实际路径 factory.setRepository(new File(serverPath)); ServletFileUpload sfupload = new ServletFileUpload(factory); sfupload.setSizeMax(10 * 1024 * 1024);// 文件最大上限 /**************************************************************************************************************/ try { // 在这里是直接获取了表单域中所有输入框的数据,在后面通过判断每一个< input > 的域值是否为上传文件,是的话就开始上传操作 @SuppressWarnings("unchecked") // 获取所有文件列表开始上传 List<FileItem> items = sfupload.parseRequest(request); for (int i = 0; i < items.size(); i++) { // 里面一个for循环,获取一行的数据 FileItem item = items.get(i); // 判断是否为表单数据 if (!item.isFormField()) {
// 文件名 String fileName = item.getName().toLowerCase(); InputStream in = item.getInputStream();
//获取上传文件的输入流,然后将输入流保存到数据库中 SqlImage.saveFile2Sql(in); request.getRequestDispatcher("showImg.jsp").forward(request, response); } else { // 如果是表单域中的数据,则直接输出表单中的数据,也可以不做处理 // String value = item.getString(); } } } catch (Exception e) { e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } }
jdbc工具类:
package sqlImgUtil; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBConnector { private static String driver = "com.mysql.jdbvc.Driver"; private static String url = "jdbc:mysql://localhost:3306/fire?"; private static String user = "root"; private static String password = ""; public static Connection getConnection() throws SQLException, ClassNotFoundException { return DriverManager.getConnection(url, user, password); }
public static void release(PreparedStatement pstmt , Connection conn , ResultSet rs) throws SQLException{
if(pstmt != null){
pstmt.close();
}
if(conn != null){
conn.close();
}
if(rs != null){
rs.close();
}
}
}
将图片保存至数据库以及输出图片数据流:
package sqlImgUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SqlImage {
public static Connection conn;
public static PreparedStatement pstmt;
public static ResultSet rs;
/**
* 将图片转化成字节流,然后以blod(sql)格式存入数据库中
*
* @param InputStream in
* @throws SQLException
* @throws IOException
* @throws ClassNotFoundException
*/
public static void saveFile2Sql(InputStream in) throws SQLException, IOException, ClassNotFoundException {
//FileInputStream fin = new FileInputStream(new File(path));
conn = DBConnector.getConnection();
String sql = "insert into image values(?,?);";
pstmt = conn.prepareStatement(sql);
pstmt.setBinaryStream(1, in, in.available());
pstmt.setInt(2, 9);
pstmt.executeUpdate();
DBConnector.release(pstmt, conn, rs);
}
/**
* 通过将从数据库中获取的图片资源转化为输入流
*
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* @return in InputStream
*/
public static InputStream getSqlImgFile() throws SQLException, FileNotFoundException, ClassNotFoundException {
conn = DBConnector.getConnection();
String sql = "select imag from image where id = 9";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
InputStream in = null;
while (rs.next()) {
Blob blob = rs.getBlob(1);
// 从数据中获取图片资源输入到输入流
in = blob.getBinaryStream();
// 可以将输入流写到BufferImage中
return in;
}
DBConnector.release(pstmt, conn, rs);
return null;
}
}
获取数据库中的图片资源显示至页面:
checkImg-->servlet记得配置
package servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import sqlImgUtil.SqlImage; /** * Servlet implementation class CheckImg */ public class CheckImg extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CheckImg() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "No-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); /***********************************************************************************************************/ BufferedImage image = null; try { image = ImageIO.read(SqlImage.getSqlImgFile()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } //Graphics g = image.getGraphics(); //加了下面这一行会在原图片上显示这个大小的700 600 大小的图片 //g.drawImage(image,0,0,700,600,null); ImageIO.write(image, "JPEG", response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
jsp文件:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <style type="text/css"> img { width: 5em; height: 5em; border-radius: 100%; } </style> </head> <body> <div class="checkImage" id="checkImage"> <h1>图片显示在这</h1>
//这里路径一定要对 <img alt="1234" src="${pageContext.request.contextPath}/CheckImg" /> </div> </body> </html>
以上是关于上传图片至数据库及从数据库中读取图片显示至页面的主要内容,如果未能解决你的问题,请参考以下文章
java实现图片上传至服务器并显示,如何做?希望要具体的代码实现
Nine——>Ten tornado操作之项目一些小改动(每页显示用户名;实现用户可以点击自己缩略图页面任一图片跳转至对应的具体图片详情页功能)