往MYSQL中插入,读写图片!

HTML 专栏收录该内容
8 篇文章 0 订阅

开发环境:MyEclipse+MySql

1,          随便找一个数据库建一张表,我这里用的是mysql数据库,

1)切换到mysql数据库:use mysql;

2)建表create table image(

name char(20) not null primary key,

image longblob

);

PS:注意存放图片那个字段的类型,为longblob,把name这个字段设置成主键,以防后面插入图片发生错误!

3)然后我们插入名字,方便查找

insert into image (name) value ('image');

 

2,其实很简单,只有三个文件:

     UploadImage.java:负责将图片存入数据库

     showImage.jsp:负责将图片从数据库中读出来

index.jsp:负责显示,插入图片等操作

先上效果图:

 

然后咱们来看整个项目的大体框架:

 

 

闲话少说,上代码:

UploadImage.java

public class UploadImage {
	String userName="root";
	String password="123456";
	Connection conn=null;
	Statement stmt=null;
	String url="jdbc:mysql://localhost:3306/mysql";
	public boolean storeImage(String path,String sql) {
		try {
			File file = new File(path);
			//打开文件
			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;
			}
			//关闭文件
			fin.close();
			//新建一个数组保存要写的内容
			byte[] content = nbf.array();
			//保存数据
			return setImage(sql, content);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//如果发生文件读写错误都会返回false
		return false;
	}

	private boolean setImage(String sqlstr, byte[] in) {
		boolean flag = false;
		if (sqlstr == null)
			sqlstr = "select * from image";
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn=DriverManager.getConnection(url,userName,password);
			stmt =
				conn.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_UPDATABLE);
			ResultSet rs = stmt.executeQuery(sqlstr);
			if (rs.next()) {
				rs.updateBytes(2, in);        //2表示更新第二个字段,即image这个字段
				rs.updateRow();
			} else {
				rs.moveToInsertRow();
				rs.updateBytes(2, in);
				rs.insertRow();
			}
			rs.close();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
}

由于JSP一直提倡java代码与jsp页面分离,java代码负责逻辑控制,jsp页面负责显示,所以我们只要我们在jsp页面调用上面那个类即可,这样jsp页面看起来就非常干净整洁!

showImage.jsp

<%@ page language="java" contentType="image/jpeg;charset=GB2312"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.awt.image.*"%>
<%@ page import="javax.imageio.*"%>
<%@ page import="com.sun.image.codec.jpeg.*"%>



<html>
  
  <head>
    <meta http-equiv="Content-Type" content="image/jpeg; charset=GB2312">
    <title>showDBImage.jsp</title>
  </head>

  <body>
<%
String userName="root";
	String password="123456";
	Connection conn=null;
	String url="jdbc:mysql://localhost:3306/mysql";
	String showImage = "select * from image where name='image';" ;
	BufferedInputStream inputImage = null;
	
	try{
		Class.forName("com.mysql.jdbc.Driver");
			conn=DriverManager.getConnection(url,userName,password);
		Statement st = conn.createStatement();
		ResultSet rs=st.executeQuery(showImage);
		while(rs.next()) {
			Blob blob = (Blob)rs.getBlob("image");
			inputImage = new BufferedInputStream(blob.getBinaryStream()); 
		}
		
  		BufferedImage image = null;
  		image=ImageIO.read(inputImage);
		
		ServletOutputStream sos = response.getOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
		encoder.encode(image);
		inputImage.close();
	} catch(SQLException se) {
		se.printStackTrace();
	} catch(IOException ie) {
		ie.printStackTrace();
	}
%>
  
  </body>

</html>


 

index.jsp

<%@ page language="java" import="java.util.*,com.njue.image.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script language="javascript" type="text/javascript">
    function login(){
          var path=document.getElementById("file");
         path.select();
     var realpath = document.selection.createRange().text;   
	if(realpath!=null&&realpath.length>0){
		var r=confirm("你确定将这张图片存入MYSQL数据库吗?");  
		if(r==true){
		window.location="index.jsp?realpath="+realpath;
		}
		}
		else{
		alert("没有选择图片!");
		}
}
</script>
  </head>
  
  <body background="background.jpg">
    <div align="center" style="margin-top:15%;">
    <%
       String realpath=request.getParameter("realpath");
       if(realpath!=null&&realpath.length()>0){
       String sql="select * from image where name='image';";
       UploadImage image=new UploadImage();
       if(image.storeImage(realpath,sql)){
     %>
     <h1>成功插入图片!</h1><br>
     <img src="showImage.jsp"/><br><br>
     <%
     }
     else{
     %>
      <h1>插入图片失败!</h1>
     <%
     }
     } 
     %>
    <input type="file" name="file"/>
    <a href=javascript:login()>确定</a>
    </div>
  </body>
</html>

 

把我期间遇到的问题列出来:

1,javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/aspectj/lang/Signature


 

如果出现这个错误,多半是mysql的驱动有问题了

mysql-connector-java-3.1.10-bin.jar

mysql-connector-java-3.1.10-bin-g.jar

大家可以看出一个后面有-g,一个没有,这里大家应该用第一个,将他复制进WebRoot/WEB-INF/lib这个文件夹中即可,

有兴趣的可以下载整个工程!

下载地址:http://download.csdn.net/detail/pzhtpf/4177978


 

  • 11
    点赞
  • 9
    评论
  • 14
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值