public Map fileUpload(HttpServletRequest request,
User user) throws IOException {
String uploadBasePath = UploadConstant.FILE_UPLOAD_BASE_PATH;
Calendar date = Calendar.getInstance();
int year = date.get(Calendar.YEAR);
int month = date.get(Calendar.MONTH)+1;
int day = date.get(Calendar.DAY_OF_MONTH);
String type = request.getParameter("imgType");
String relativePath = tempUploadImage + "/" + year +"/"+ month +"/" +day+ "/"+type+"/";
String uploadPath = uploadBasePath + relativePath;
Map uploadResult = UpDownFileUtil.multiFileUpload(request, uploadPath);
for (String imagePath : uploadResult.keySet()) {
uploadResult.put(imagePath, uploadResult.get(imagePath).replace(new File(uploadBasePath).getPath(), "").replaceAll("\\\\", "/"));
}
String imagePaths = uploadResult.toString();
imagePaths = imagePaths.substring(1, imagePaths.length()-1);
String[] imagePathArray = imagePaths.split(",");
if(imagePathArray.length <= 1){
String[] image = imagePathArray[0].split("=");
uploadResult.put("theImgName", image[0]);
uploadResult.put("theImgPath", image[1]);
}
return uploadResult;
}
以下方法都存放在上传文件工具类中
---------------------------------------------------------------------------------------------------------------
//多文件上传
public static Map multiFileUpload(HttpServletRequest request, String basePath) throws IllegalStateException, IOException {
File baseFile = new File(basePath);
//判断文件是否存在
if(!baseFile.exists()){
baseFile.mkdirs(); //mkdirs()方法可以建好一个完整的路径. mkdir() 只能在已经存在的目录中创建创建文件夹。
}
//检查一个对象是否是文件夹
if (!baseFile.isDirectory()) {
throw new IllegalArgumentException("basePath 参数必须是文件夹路径");
}
return multifileUploadAssist(request, basePath, null);
}
//多文件上传辅助
private static Map multifileUploadAssist(HttpServletRequest request, String basePath, String exclude) throws IOException {
exclude = exclude == null ? "" : exclude;
Map filePaths = new HashMap();
File file = null;
// 创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// get the parameter names of the MULTIPART files contained in this request
Iterator iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
List multipartFiles = multiRequest.getFiles(iter.next());
for (MultipartFile multipartFile : multipartFiles) {
String fileName = multipartFile.getOriginalFilename();
if (StringUtils.isNotEmpty(fileName) && (!exclude.contains(fileName))) {
file = new File(basePath + changeFilename2UUID(fileName));
filePaths.put(fileName, file.getPath());
multipartFile.transferTo(file);
}
}
}
}
return filePaths;
}