日期:2014-05-17 浏览次数:20846 次
/**
* 上传文件的监听器
* @author xjl
* @version 2.0
*/
public class UploadListener implements ProgressListener {
private UploadInfo info;
/**
* 构造方法
* @param session
*/
public UploadListener(HttpSession session) {
info = (UploadInfo) session.getAttribute(FrameConfig.uploadInfo);
if (null == info) {
info = new UploadInfo();
}
session.setAttribute(FrameConfig.uploadInfo, info);
}
/**
* 上传文件即时监听
* @param readSize 已上传字节数
* @param fileSize 文件总大小
* @param num 目前正在读取第几个文件
*/
public void update(long readSize, long fileSize, int num) {
if (num > 0) {
Double percent = ( ((Long) readSize).doubleValue() / ((Long) fileSize).doubleValue()) * 100d;
info.setFileSize(fileSize);
info.setNum(num);
info.setPercent(percent.intValue());
info.setReadSize(readSize);
}
}
}
/**
* 上传文件, 返回上传成功的文件个数, 可以读取文件上传的实时进度
* @param folder 文件存放的目录,物理路径
* @param newFileName 保存为新文件的名称(支持多个文件同时上传)
* @return int
*/
@SuppressWarnings("unchecked")
public int uploadFile(String folder, String []newFileName) {
int num = -1;
try {
File folderFile = new File(folder);
FileUtil.getBean().createFolder(folder);
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(FrameConfig.maxUploadFileSize);
upload.setProgressListener(new UploadListener(getSession()));
getRequest().setCharacterEncoding("UTF-8");
Iterator iterator = upload.parseRequest(getRequest()).iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();//源文件
if (!item.isFormField() && !"".equals(item.getName())) {
num++;
if (num < newFileName.length) {
OutputStream output = new FileOutputStream(new File(folderFile, newFileName[num]));
InputStream input = item.getInputStream();
try {
byte[] buffer = new byte[1024];
int i = 0;
while ((i = input.read(buffer)) != -1) {
output.write(buffer, 0, i);//保存文件
}
} catch (Exception e) {
e.printStackTrace();
} finally {