📄 accessorydaoimpl.java
字号:
package com.wygl.fjgl.service;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.opensymphony.util.GUID;
import com.opensymphony.webwork.ServletActionContext;
import com.wygl.fjgl.domain.Accessory;
import com.wygl.fjgl.util.FolderCreateException;
import com.wygl.fjgl.util.OperateFileFolder;
/**
* Blob对象数据库存取服务实现
*/
public class AccessoryDaoImpl implements AccessoryDao {
private Connection con;
private HttpServletRequest request;
private HttpServletResponse response;
private ServletConfig config;
private SmartUpload uploadUtil;
private String realPath;
private final long MAXFILESIZE = 20*1024*1024;
private final long TOTALMAXFILESIZE = 100*1024*1024;
private final String UPLOADPATH = "upload\\";
/**
* 初始化变量
*/
private void initializeVariable() throws Exception{
try {
con = dataSource.getConnection();
} catch (Exception e1) {
e1.printStackTrace();
throw new Exception("数据源初始化错误.");
}
request = ServletActionContext.getRequest();
response = ServletActionContext.getResponse();
config = ServletActionContext.getServletConfig();
realPath = ServletActionContext.getServletContext().getRealPath("/");
}
/**
* 初始化上传下载对象
*/
private void initializeUpload() throws Exception{
try {
initializeVariable();
} catch (Exception e2) {
throw new Exception("数据源初始化错误.");
}
//上传初始化
try {
uploadUtil = new SmartUpload();
uploadUtil.initialize(config, request, response);
} catch (Exception e1) {
e1.printStackTrace();
throw new Exception("文件上传对象初始化错误.");
}
//设定上传限制
// 1.限制每个上传文件的最大长度。
uploadUtil.setMaxFileSize(MAXFILESIZE);
// 2.限制总上传数据的长度。
uploadUtil.setTotalMaxFileSize(TOTALMAXFILESIZE);
//上传文件
try {
uploadUtil.upload();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("<table><tr><td align='left'>附件上传失败:<br>"
+"1.单个上传文件的最大长度超过"+MAXFILESIZE+"字节;<br>"
+"2.总上传文件的长度超过"+TOTALMAXFILESIZE+"字节.</td></tr></table>");
}
}
/**
* 检查上传文件的合法性(总文件大小,单个文件大小,允许上传文件类型)
* @param upFiles (Accessory对象)
* @return List (Accessory对象)
* @throws Exception
*/
private List checkOutUpfiles(List upFiles) throws Exception{
//返回对象(表单字段名称,Accessory对象)
List rtnList = new ArrayList();
//所有上传文件的集合
Files files = uploadUtil.getFiles();
//检查上传文件数目
if(files.getCount() == 0) throw new Exception("上传文件数目为0个.");
//检查上传文件大小总和
long totalMaxFileSize = files.getSize();
if(totalMaxFileSize > TOTALMAXFILESIZE) throw new Exception("上传文件大小总和超过"+TOTALMAXFILESIZE+"字节.");
//检查上传文件参数为空
if(upFiles == null) throw new Exception("上传文件参数为空.");
//逐个检查上传文件
for(int i=0;i<upFiles.size();i++){
Accessory accessory = (Accessory)upFiles.get(i);
//逐个文件进行对应生成,并进行相应检查校验
for (int j=0;j<files.getCount();j++){
com.jspsmart.upload.File fileManger = files.getFile(j);
if(fileManger.getFieldName().equals(accessory.getFieldName())){
//判断文件表单字段是否为空既没有选择文件或选择的文件不正确
if (fileManger.isMissing() || fileManger.getSize() <=0 ){
//没有选择文件,即对应的表单项没有值;选择文件大小小于0
}else{
//选择了文件
int fileSize = fileManger.getSize();
if (fileSize > MAXFILESIZE) throw new Exception(accessory.getFieldNameZh()+"文件大小超过"+MAXFILESIZE+"字节.");
if(accessory.getAccessory_id() == null || accessory.getAccessory_id().equals("")){
accessory.setAccessory_id(GUID.generateFormattedGUID());
accessory.setType("0");
}else{
accessory.setType("1");
}
//在服务器上生成临时文件夹
try {
OperateFileFolder.getInstance().deleteFileFold(realPath+UPLOADPATH+accessory.getAccessory_id()+"\\");
} catch (Exception e2) {
e2.printStackTrace();
throw new Exception("为"+accessory.getFieldNameZh()+"删除文件夹错误.");
}
try {
OperateFileFolder.getInstance().createFileFold(realPath+UPLOADPATH+accessory.getAccessory_id());
} catch (FolderCreateException ex) {
ex.printStackTrace();
throw new Exception("为"+accessory.getFieldNameZh()+"创建文件夹错误.");
} catch (Exception e) {
e.printStackTrace();
throw new Exception("为"+accessory.getFieldNameZh()+"创建文件夹错误,文件名称重复.");
}
//在服务器上生成临时文件
String filepath = realPath+UPLOADPATH+accessory.getAccessory_id()+"\\"+fileManger.getFileName();
try {
fileManger.saveAs(filepath);
} catch (Exception e) {
throw new Exception("为"+accessory.getFieldNameZh()+"创建文件错误.");
}
//读取文件对象
java.io.File file = new java.io.File(filepath);
//给accessory对象赋值
accessory.setFileName(fileManger.getFileName());
accessory.setFileExtName(fileManger.getFileExt());
accessory.setFilSize(fileManger.getSize());
accessory.setAccessory(file);
rtnList.add(accessory);
}
}else{
continue;
}
}
}
return rtnList;
}
/**
* 清除临时文件和临时变量
* @param upFiles (Accessory对象)
* @throws Exception
*/
private void clearUpfiles(List upFiles) throws Exception{
try {
//逐个检查上传文件
for(int i=0;i<upFiles.size();i++){
Accessory accessory = (Accessory)upFiles.get(i);
//在服务器上生成临时文件夹
OperateFileFolder.getInstance().deleteFileFold(realPath+UPLOADPATH+accessory.getAccessory_id()+"\\");
}
} catch (Exception e2) {
e2.printStackTrace();
throw new Exception("删除文件夹错误.");
}finally{
con.close();
uploadUtil.stop();
uploadUtil = null;
}
}
/**
* 添加保存文件到数据库
* @param java.io.File file
* @throws Exception
*/
private void addUpfile(Accessory accessory) throws Exception{
try {
java.io.FileInputStream fis = new java.io.FileInputStream(accessory.getAccessory());
PreparedStatement ps = con.prepareStatement("insert into FJGL_Accessory(accessory_id,name,size,accessory,ext) values(?,?,?,?,?)");
ps.setString(1, accessory.getAccessory_id());
ps.setString(2, accessory.getFileName());
ps.setLong(3, accessory.getFilSize());
ps.setBinaryStream(4, fis, (int) accessory.getAccessory().length());
ps.setString(5, accessory.getFileExtName());
con.setAutoCommit(true);
ps.executeUpdate();
con.commit();
fis.close();
ps.close();
} catch (FileNotFoundException e) {
throw new Exception("添加文件时,找不到文件."+e.getMessage());
} catch (SQLException e) {
con.rollback();
throw new Exception("执行添加文件到数据库出错."+e.getMessage());
}
}
/**
* 更新保存文件到数据库
* @param java.io.File file
* @throws Exception
*/
private void updateUpfile(Accessory accessory) throws Exception{
try {
java.io.FileInputStream fis = new java.io.FileInputStream(accessory.getAccessory());
PreparedStatement ps = con.prepareStatement("update FJGL_Accessory set name=?,size=?,accessory=?,ext=? where accessory_id=?");
ps.setString(1, accessory.getFileName());
ps.setLong(2, accessory.getFilSize());
ps.setBinaryStream(3, fis, (int) accessory.getAccessory().length());
ps.setString(4, accessory.getFileExtName());
ps.setString(5, accessory.getAccessory_id());
con.setAutoCommit(true);
ps.executeUpdate();
con.commit();
fis.close();
ps.close();
} catch (FileNotFoundException e) {
throw new Exception("添加文件时,找不到文件."+e.getMessage());
} catch (SQLException e) {
con.rollback();
throw new Exception("执行添加文件到数据库出错."+e.getMessage());
}
}
/**
* 数据源
*/
private DataSource dataSource;
/**
* 上传文件
* @param upFiles (Accessory对象)
* @return List (Accessory对象)
* @throws Exception
*/
public List upload(List upFiles) throws Exception {
List files = new ArrayList();
//初始化变量
try {
initializeUpload();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
//检查上传文件的合法性
try {
files = checkOutUpfiles(upFiles);
} catch (Exception e) {
throw new Exception(e.getMessage());
}
//保存或更新文件
try {
for(int i=0;i<files.size();i++){
Accessory accessory = (Accessory)upFiles.get(i);
if(accessory.getType().equals("0")){
addUpfile(accessory);
}else if(accessory.getType().equals("1")){
updateUpfile(accessory);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
//清除临时文件和临时变量
try {
clearUpfiles(files);
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return files;
}
/**
* 删除文件附件
* @param accessory_id
* @return boolean
* @roseuid 432F713C033B
*/
public boolean delete(String accessory_id) throws Exception {
try {
con = dataSource.getConnection();
Statement st = con.createStatement();
st.execute("delete from FJGL_Accessory where accessory_id='"+accessory_id+"'");
con.commit();
return true;
} catch (Exception e) {
con.rollback();
throw new Exception("执行删除文件到数据库出错."+e.getMessage());
}finally{
con.close();
}
}
/**
* 备份文件
* @param accessory_id
* @return String
* @roseuid 432F713C03A1
*/
public String backupFile(String accessory_id) throws Exception {
String bakAccessory_id = GUID.generateFormattedGUID();
//初始化变量
try {
initializeVariable();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select name,size,ext,accessory from FJGL_Accessory where accessory_id='"+accessory_id+"'");
InputStream in = null;
String fileName = "";
long size = 0;
String ext = "";
if(rs.next()){
fileName = getFileName(rs.getString("name"));
size = rs.getLong("size");
ext = rs.getString("ext");
in = rs.getBinaryStream("accessory");
}
if(fileName != null && !fileName.equals("")){
PreparedStatement ps = con.prepareStatement("insert into FJGL_Accessory(accessory_id,name,size,accessory,ext) values(?,?,?,?,?)");
ps.setString(1, bakAccessory_id);
ps.setString(2, fileName);
ps.setLong(3, size);
ps.setBinaryStream(4, in, (int)size);
ps.setString(5, ext);
con.setAutoCommit(true);
ps.executeUpdate();
con.commit();
ps.close();
in.close();
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
con.rollback();
throw new Exception("备份文件出错."+e.getMessage());
}finally{
con.close();
}
return bakAccessory_id;
}
/**
* 下载文件
* @param accessory_id
* @return List
* @roseuid 432F713C03A0
*/
public List download(String accessory_id) throws Exception {
List list = new ArrayList();
//初始化变量
try {
initializeVariable();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select name,accessory from FJGL_Accessory where accessory_id='"+accessory_id+"'");
if(rs.next()){
String fileName = getFileName(rs.getString("name"));
InputStream in = rs.getBinaryStream("accessory");
list.add(fileName);
list.add(in);
list.add(con);
}
} catch (Exception e) {
throw new Exception("从数据库下载文件出错."+e.getMessage());
}
return list;
}
/**
* 获取文件中文名称
* @param filePathName
* @return
*/
private String getFileName(String filePathName){
int pos = 0;
pos = filePathName.lastIndexOf(47);
if(pos != -1)
return filePathName.substring(pos + 1, filePathName.length());
pos = filePathName.lastIndexOf(92);
if(pos != -1)
return filePathName.substring(pos + 1, filePathName.length());
else
return filePathName;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -