批量将上传文件保存至数据库同时保存至磁盘import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;import com.freedom.common.PageCtrlDTO;
import com.freedom.db.DBUtils;
import com.netcast.business.system.web.form.SystemHelpActionForm;
import com.netcast.util.DBManager;
import com.netcast.util.StringUtils;
import com.netcast.util.exception.common.DBManagerException;
import com.netcast.util.exception.common.FileDAOException;
import com.netcast.util.exception.program.ProgramDAOException;
import com.netcast.vo.AccessoryVO;/**
 * 上传下载文件 数据库操作<br>
 * Author:sun<br>
 * CreateDate:2008-01-30<br>
 * Modifier:sun<br>
 * ModifyDate:2008-01-30<br>
 * Version:1.0<br>
 * Copyright(c)2008 深蓝工作室<br>
 * All right reserved.<br>
 */
public class FileDAO
{
private static final Logger logger = Logger.getLogger(LoginDAO.class);
/**
 * 批量上传附件<br>
 * Author:BluesLee<br>
 * CreateDate:2008-03-08<br>
 * Modifier:BluesLee<br>
 * ModifyDate:2008-03-08<br>
 * Version:1.0<br>
 * 
 * @param accessoryVOList
 * @param filePath
 * @throws FileDAOException
 */
public void uploadFileList(List<AccessoryVO> accessoryVOList, String filePath) throws FileDAOException
{
Connection conn = null; try
{
conn = DBUtils.getConn();//获取数据库连接
conn.setAutoCommit(false); // 写数据库
this.uploadFile(accessoryVOList, conn);
// 写磁盘
String result = writeFiletoDisk(accessoryVOList, filePath);
// 返回上传失败信息
if (result != null)
{
logger.error("上传失败! " + result);
throw new FileDAOException(result);
} conn.commit();
}
catch (Exception e)
{
try
{
conn.rollback();
}
catch (SQLException eRllBack)
{
logger.error("上传附件失败!" + eRllBack);
throw new FileDAOException(eRllBack.getMessage(), eRllBack);
} logger.error("上传附件失败!" + e);
throw new FileDAOException(e.getMessage(), e);
}
finally
{
try
{
conn.setAutoCommit(true);
//关闭数据库资源
DBManager.getInstance().closeAll(conn, null, null, null, null);
}
catch (DBManagerException e)
{
logger.error("关闭数据库资源错误:" + e);
throw new FileDAOException(e.getMessage(), e);
}
catch (SQLException e)
{
logger.error("设置事务为自动处理失败," + e);
throw new FileDAOException("设置事务为自动处理失败," + e.getMessage(), e);
}
}
} /**
 * 上传附件写入数据库<br>
 * Author:BluesLee<br>
 * CreateDate:2008-03-08<br>
 * Modifier:BluesLee<br>
 * ModifyDate:2008-01-08<br>
 * Version:1.0<br>
 * 
 * @param accessoryVOList 上传文件信息集合
 * @param conn 数据库连接
 * @return
 * @throws FileDAOException
 */
public void uploadFile(List<AccessoryVO> accessoryVOList, Connection conn) throws FileDAOException
{
PreparedStatement insertPs = null;
PreparedStatement queryPs = null;
ResultSet queryRs = null;
try
{
// 执行新增
String insertSQL = " insert into m_accessory (acc_no, acc_type, mis_no, file_title, real_name, blob_file, upload_date, is_deleted) "
+ " VALUES (m_accessory_seq.nextval,?,?,?,?,EMPTY_BLOB(),sysdate,0)";
// 查询插入BLOB值
StringBuffer querySQL = new StringBuffer(
"select a.real_name,a.blob_file from m_accessory a where a.real_name in ("); String join = "";
insertPs = conn.prepareStatement(insertSQL);
for (int i = 0; i < accessoryVOList.size(); i++)
{
AccessoryVO accessoryVO = accessoryVOList.get(i); int index = 1;
insertPs.setString(index, accessoryVO.getAcc_type());
index = index + 1;
insertPs.setLong(index, accessoryVO.getMis_no());
index = index + 1;
insertPs.setString(index, accessoryVO.getFile_title());
index = index + 1;
insertPs.setString(index, accessoryVO.getReal_name()); insertPs.addBatch();
querySQL.append(join);
querySQL.append("?");
join = ",";
}
querySQL.append(") for update");
insertPs.executeBatch();
// 查询插入BLOB字段数据
queryPs = conn.prepareStatement(querySQL.toString());
HashMap<String, AccessoryVO> fileMap = new HashMap<String, AccessoryVO>();
for (int i = 0; i < accessoryVOList.size(); i++)
{
AccessoryVO accessoryVO = accessoryVOList.get(i); queryPs.setString(i + 1, accessoryVO.getReal_name());
fileMap.put(accessoryVO.getReal_name(), accessoryVO);
}
queryRs = queryPs.executeQuery();
if (queryRs != null)
{
OutputStream fileOut = null;
InputStream fileIn = null;
while (queryRs.next())
{
String real_name = queryRs.getString("real_name");
Blob blob_file = queryRs.getBlob("blob_file"); AccessoryVO accessoryVO = fileMap.get(real_name);
if (accessoryVO != null && accessoryVO.getFile() != null)
{
// 建立输出流
fileOut = blob_file.setBinaryStream(0);
// 建立输入流
fileIn = accessoryVO.getFile().getInputStream();
// 建立缓冲区
byte[] buffer = new byte[1024];
// 循环写入
int len = 0;
while ((len = fileIn.read(buffer)) != -1)
{
fileOut.write(buffer, 0, len);
}
// 关闭操作流
fileIn.close();
fileIn = null;
fileOut.close();
fileOut = null;
}
}
}
}
catch (IOException e)
{
logger.error("上传附件失败,流操作错误," + e);
new FileDAOException("上传附件失败,流操作错误," + e.getMessage(), e);
}
catch (SQLException e)
{
logger.error("上传附件失败,数据库错误," + e);
new FileDAOException("上传附件失败,数据库错误," + e.getMessage(), e);
}
finally
{ try
{
//关闭数据库资源
DBManager.getInstance().closeAll(null, null, insertPs, null, null);
DBManager.getInstance().closeAll(null, null, queryPs, null, queryRs);
}
catch (DBManagerException e)
{
logger.error( e);
throw new FileDAOException(e.getMessage(), e);
} }
} /**
 * 写磁盘文件<br>
 * Author:BluesLee<br>
 * CreateDate:2008-03-08<br>
 * Modifier:BluesLee<br>
 * ModifyDate:2008-03-08<br>
 * Version:1.0<br>
 * 
 * @param accessoryVOList
 * @param filePath
 * @return
 * @throws FileDAOException
 */
public String writeFiletoDisk(List<AccessoryVO> accessoryVOList, String filePath) throws FileDAOException
{ String result = null; try
{
// 过滤文件路径"/"
filePath=filePath.replaceAll("/+", "/");
filePath=filePath.replaceAll("\\\\+", "\\\\");
// 上传文件目录不存在的时候,创建该目录
File upload_folder = new File(filePath);
if (!upload_folder.exists())
{
upload_folder.mkdirs();
} // 循环上传
for (int i = 0; i < accessoryVOList.size(); i++)
{
AccessoryVO accessoryVO = accessoryVOList.get(i);
FormFile nowFile = (FormFile) accessoryVO.getFile();// 文件 File file = new File(filePath + accessoryVO.getReal_name());
FileOutputStream fos = new FileOutputStream(file);
fos.write(nowFile.getFileData());
fos.close();
}
}
catch (Exception e)
{
// 抛出异常,并删除之前文件
result = "写磁盘文件 失败!";
for (int i = 0; i < accessoryVOList.size(); i++)
{
AccessoryVO accessoryVO = accessoryVOList.get(i); File file = new File(filePath + accessoryVO.getReal_name());
if (file.exists()) file.delete();
}
logger.error( result + e);
throw new FileDAOException(result);
}
return result;
}
}

解决方案 »

  1.   

    谢谢三楼的回答
    我看了你的代码,好像使用的common-fileupload,那几个jar文件应该放在那里啊,我用的是jdeveloper开发的,没有tomact,该怎么放那几个jar文件呢?
      

  2.   

    里面有r_id<pk>,h_id<外键>,r_photo<blob类型>,r_price,r_describe,r_area
    使用的是oracle数据库
      

  3.   

    http://download.csdn.net/source/644581
    你看看这个好用吗 看看能不能帮助你
      

  4.   

    现在我使用common-fileupload组件能够实现文件上传了,在网上找的好多都是传到的文件夹里面,可以传到服务器文件夹里面吗?然后数据库存取图片的路径,这样的代码谁有啊?谢谢贴一个