1. 程式人生 > >如何用JAVA將二進位制檔案轉換成BASE64格式儲存到MySQL的Blob欄位裡並讀出下載

如何用JAVA將二進位制檔案轉換成BASE64格式儲存到MySQL的Blob欄位裡並讀出下載

由於需求要將上傳的檔案以BASE64的方式儲存到MySQL的Blob欄位,並可以讀取Blob欄位下載生成檔案,方法如下:

1、下載用於BASE64編碼轉換的sun.misc.BASE64Decoder和sun.misc.BASE64Encoder的支援庫(jar),放到執行庫中。

2.   實現程式碼如下:

package com.pszx.venus;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;



import com.pszx.venus.DBConnector;
import com.sun.org.apache.xml.internal.security.utils.Base64;



public class upLoadFileToDB {
	
	public void upLoadFile() throws Exception{
		String fileName = "d:\\finish3.png";
		
		File file = new File(fileName);
		FileInputStream fin = new FileInputStream(file);
		
		byte[] buffer = new byte[(int)file.length()];
		
		fin.read(buffer);
		fin.close();
		
		DBConnector dbc = new DBConnector();
		Connection conn = dbc.createConn();
		PreparedStatement pstmt = null;
		conn.setAutoCommit(false);
		
		String sql = "";
		try{
		
			String sql1 = "update sample set fj=?, bz=?  where id=1 ";
			
			pstmt = conn.prepareStatement(sql1);
			pstmt.setString(1, new BASE64Encoder().encode(buffer));  //將檔案內容編碼成base64格式後以字串的方式儲存到Blob欄位中
pstmt.setString(2, "wilson"); pstmt.executeUpdate(); conn.commit(); //從資料庫中讀出 sql1 = "select fj from sample where id=1"; pstmt = conn.prepareStatement(sql1); ResultSet rs = pstmt.executeQuery(); byte[] binfl = null; while(rs.next()){ Blob b = rs.getBlob("fj"); //從Blob欄位中讀出base64格式的內容
byte[] ba = b.getBytes(1, (int)b.length()); binfl = Base64.decode(ba); //將base64格式解碼 } String fileName1= "d:\\finish4.png"; File file1 = new File(fileName1); FileOutputStream fout = new FileOutputStream(file1); fout.write(binfl); //將解碼後的內容寫入檔案
fout.close(); }finally{ pstmt.close(); conn.close(); dbc.disConnect(); } } public static void main(String[] args) throws Exception{ upLoadFileToDB lf = new upLoadFileToDB(); lf.upLoadFile(); } }