如何用JAVA将二进制文件转换成BASE64格式保存到MySQL的Blob字段里并读出下载

来源:互联网 发布:故宫 淘宝 彩妆 编辑:程序博客网 时间:2024/06/05 09:16

由于需求要将上传的文件以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();}}



阅读全文
0 0