1. 程式人生 > >上傳圖片至數據庫及從數據庫中讀取圖片顯示至頁面

上傳圖片至數據庫及從數據庫中讀取圖片顯示至頁面

for循環 common 基於 serial 文件創建 每一個 super lis size

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>

上傳圖片至數據庫及從數據庫中讀取圖片顯示至頁面