原生js和servlet将图片存入数据库和读取

最近在做公司项目的时候,有个小功能需要将图片存入数据库。可能大家觉得奇怪,还有人把图片存入数据库。当时我接受这个需求的时候也快疯了,一般都是只存图片路径的,但是人家这么要求只能照办了。当时在网上找了半天,终于得以解决。

其实,数据库是可以存二进制文件。所以,先获取图片的二进制数组,然后直接插入数据库。当读的时候,获得的是Blob对象,跟据Blob对象获得二进制数据,二进制数组都拿到了,那还不是为所欲为。

不说了,直接上代码吧:jar包下载地址https://download.csdn.net/my

一、前段代码,HTML部分



	
		
		
	
	
		
  	    
  	    

js部分


二、后端代码(存入部分)

package my.imgUpload.demo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.sql.BLOB;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

public class ImgUploadServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request , response);
	}
	

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			doUpload(request , response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	public void doUpload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String result = null;
		boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
		if(!isMultiPart)
			throw new Exception("请求编码必须为: multipart/form-data !");
		request.setCharacterEncoding("utf-8");
		ServletFileUpload upload = new ServletFileUpload();
		FileItemIterator it = upload.getItemIterator(request);
		while(it.hasNext())
		{
			//表单域
			FileItemStream item = it.next();
			String fileName = item.getFieldName();
			InputStream fieldStream = item.openStream();
			//普通的表单域则直接读取
			if(item.isFormField())
			{
				String fieldValue = Streams.asString(fieldStream , "utf-8");
				System.out.println("表单域:" + fileName + "=" + fieldValue);
			}
			else
			{
				System.out.println("上传的文件名为:" + item.getName());
				result = item.getName();
				//建立缓冲
				ByteArrayOutputStream cache = new ByteArrayOutputStream();
				byte[] b = new byte[1024];
				//读取数据
				while(true)
				{
					int n = fieldStream.read(b);
					if(n == 0)
						continue;
					if(n<0)
						break;
					cache.write(b, 0, n);					
				}
				byte[] byts = cache.toByteArray();
				saveImg(byts);
				OutputStream out = response.getOutputStream();
				out.write(result.getBytes());
				out.close();				
			}

		}
		
	}

	//链接数据库将图片存进数据库
	public void saveImg(byte[] bytes)
	{
		
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//加载驱动
			Class.forName("oracle.jdbc.OracleDriver");
			
			//链接数据库
			conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "scott", "tiger");
			System.out.println("链接成功!");
			//编写sql
			String sql = "INSERT INTO PERSON (name , img) VALUES (?,?)";
			//装在sql
			ps = conn.prepareStatement(sql);
			//给问号赋值
			ps.setString(1, "唐马儒23");
			ps.setBytes(2, bytes);
			
			int row = ps.executeUpdate();
			System.out.println("成功插入:"+row);
			
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(ps!=null)
			{
				try {
					ps.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(conn!=null)
			{
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	
}

(读取部分)

package my.imgUpload.demo;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetImgServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request , response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		getImg(request , response);
	}
	public void getImg(HttpServletRequest request, HttpServletResponse response)
	{
		Connection conn = null;
		PreparedStatement ps = null;
		OutputStream out = null;
		ResultSet rs = null;
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl" , "scott" , "tiger");
			//构造sql
			String sql = "select name , img from person";
			//装在sql
			ps = conn.prepareStatement(sql);
		    rs = ps.executeQuery();
			//处理结果集
		    rs.next();
			Blob blob = rs.getBlob("img");
			byte[] bytes = blob.getBytes(1, (int)blob.length());
			//获取输出流
		    out = response.getOutputStream();
			out.write(bytes);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
			       if(out!=null)
					out.close();
			       if(rs!=null)
			    	 rs.close();
			       if(ps!=null)
			    	   ps.close();
			       if(conn!=null)
			    	   conn.close();			    	   
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

}

当然,代码有不足之处,希望各位大神指教。

你可能感兴趣的:(个人学习总结)