public List<FilePathModel> upLoadFiles(HttpServletRequest request)
throws IllegalStateException, IOException {
FileOutputStream os = null;
InputStream in = null;
String systemPath = ToolUtils.filePath();
List<FilePathModel> ls = new ArrayList<FilePathModel>();
StringBuffer rootPathBuff=new StringBuffer();
rootPathBuff.append(systemPath);
rootPathBuff.append(Constant.WORK_ATTACHMENT).append(File.separator);
rootPathBuff.append(DateUtil.getDateFormatString(Calendar.getInstance().getTime(), "yyyyMM"));
File rootPath = new File(rootPathBuff.toString());
// 如果文件夹不存在则创建
if (!rootPath.exists()) {
rootPath.mkdirs();
}
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
try {
// 取得request中的所有文件
List<MultipartFile> iter = multiRequest.getFiles("files");
FilePathModel filePathModel=null;
for(int i=0;i<iter.size();i++) {
// 取得上传文件
MultipartFile file = iter.get(i);
if (file != null) {
// 取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (!ToolUtils.isEmpty(myFileName.trim())) {
filePathModel=new FilePathModel();
filePathModel.setFileName(myFileName);
String filePath = new StringBuffer(
Constant.WORK_ATTACHMENT)
.append(File.separator)
.append(DateUtil.getDateFormatString(Calendar.getInstance().getTime(), "yyyyMM"))
.append(File.separator)
.append(UUID.randomUUID())
.append(new Date().getTime()).append("_")
.append(myFileName).toString();
// 定义上传路径
filePath = systemPath + filePath;
os = new FileOutputStream(filePath);
// 拿到上传文件的输入流
in = file.getInputStream();
// 创建一个缓冲区
byte buffer[] = new byte[1024];
// 判断输入流中的数据是否已经读完的标识
int len = 0;
// 循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
while ((len = in.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
filePathModel.setFilePath(filePath);
ls.add(filePathModel);
if (os != null) {
os.flush();
os.close();
}
if (in != null) {
in.close();
}
}
}
}
} catch (Exception e) {
logger.warn("上传文件失败:{}", e.getMessage());
} finally {
try {
if (os != null) {
os.flush();
os.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
logger.error("IO关闭异常", e);
}
}
}
return ls;
}