/**
* 按照自己的规则重命名上传文件
* @author:qiuchen
* @createTime:2012-6-19
* @param name
* @return 命名后的文件名
*/
private static String rename(String name){
Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
Long random = (long) (Math.random() * now);
String fileName = now + "" + random;
if (name.indexOf(".") != -1) {
fileName += name.substring(name.lastIndexOf("."));
}
return fileName;
}
/**
* 压缩后的文件名
* @author:qiuchen
* @createTime:2012-6-19
* @param name
* @return
*/
private static String zipName(String name) {
String prefix = "";
if (name.indexOf(".") != -1) {
prefix = name.substring(0, name.lastIndexOf("."));
} else {
prefix = name;
}
return prefix + ".zip";
}
/**
* 批量上传文件
* 把上传文件压缩后保存到服务器
* @author:qiuchen
* @createTime:2012-6-19
* @param request
* @param params
* @param values
* @return
* @throws Exception
*/
public static List<Map<String, Object>> upload(HttpServletRequest request,
String[] params, Map<String, Object[]> values) throws Exception {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
//文件处理器
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
//上传文件集合
Map<String, MultipartFile> fileMap = mRequest.getFileMap();
//获取文件存放地址(文件夹)
String uploadDir = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;
//创建文件夹
File file = new File(uploadDir);
if (!file.exists()) {
file.mkdir();
}
String fileName = null;
int i = 0;
for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); i++) {
Map.Entry<String, MultipartFile> entry = it.next();
MultipartFile mFile = entry.getValue();
//原始文件名
fileName = mFile.getOriginalFilename();
//文件重命名
String storeName = rename(fileName);
//文件全路径
String noZipName = uploadDir + storeName;
//获取压缩文件的路径
String zipName = zipName(noZipName);
// 上传成为压缩文件
ZipOutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipName)));
outputStream.putNextEntry(new ZipEntry(fileName));
//从流中复制出来
FileCopyUtils.copy(mFile.getInputStream(), outputStream);
Map<String, Object> map = new HashMap<String, Object>();
// 固定参数值对
map.put(FileOperateUtil.REALNAME, zipName(fileName));
map.put(FileOperateUtil.STORENAME, zipName(storeName));
map.put(FileOperateUtil.SIZE, new File(zipName).length());
map.put(FileOperateUtil.SUFFIX, "zip");
map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");
map.put(FileOperateUtil.CREATETIME, new Date());
// 表单参数值对
for (String param : params) {
map.put(param, values.get(param)[i]);
}
result.add(map);
}
return result;
}