import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class FileDao {
/**
* 上传pdf文件
* @param file
* @param name
* @throws SQLException
* @throws ClassNotFoundException
*/
public void upload(File file,String name,Integer id) throws SQLException, ClassNotFoundException {
Files f =new Files(id,getBytesFromFile(file),name);
add(f);
}
/**
* 下载pdf文件
* @param id
* @param filepath
*/
public void download(Integer id,String filepath) throws SQLException, ClassNotFoundException {
BytestoPdffile(getfilesById(id).getFileDate(),filepath);
}
/**
* 将二进制流数据存入数据库
* @param file
* @throws ClassNotFoundException
* @throws SQLException
*/
public void add(Files file) throws ClassNotFoundException, SQLException {
Connection conn = JdbcUtil.getConnection();
String sql = "update patent set file_date=?,file_name=? where id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setBytes(1,file.getFileDate());
ps.setString(2,file.getFileName());
ps.setInt(3,file.getId());
ps.executeUpdate();
JdbcUtil.close(ps, conn);
}
/**
* 根据id获得文件二进制数据流
* @param id
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public Files getfilesById(Integer id) throws ClassNotFoundException, SQLException {
Connection conn = JdbcUtil.getConnection();
String sql = "select id,file_date,file_name from filetest where id =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,id);
ResultSet rs = ps.executeQuery();
Files file=null;
while(rs.next()){
file=new Files(rs.getInt(1), rs.getBytes(2), rs.getString(3));
}
JdbcUtil.close(ps, conn);
return file;
}
/**
* 处理文件输出二进制数据流
* @param file
* @return
*/
public byte[] getBytesFromFile(File file){
if (file == null){
return null;
}
try {
FileInputStream stream = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = stream.read(b)) != -1)
out.write(b, 0, n);
stream.close();
out.close();
return out.toByteArray();
} catch (IOException e){
}
return null;
}
/**
* 将二进制数据流转为pdf文件
* param filepath 保存路径
* @param bytes
* @param filepath
*/
public void BytestoPdffile(byte[] bytes,String filepath){
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try{
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
bis=new BufferedInputStream(byteArrayInputStream);
File file=new File(filepath);
File path=file.getParentFile();
if(!path.exists()){
path.mkdirs();
}
fos=new FileOutputStream(file);
bos=new BufferedOutputStream(fos);
byte[] buffer=new byte[1024];
int length=bis.read(buffer);
while(length!=-1){
bos.write(buffer,0,length);
length=bis.read(buffer);
}
bos.flush();
}catch(Exception e){
e.printStackTrace();
}finally {
try{
bis.close();
bos.close();
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
MySql数据库存储pdf文件
最新推荐文章于 2024-05-07 09:37:25 发布