java中图片上传

public Map<String, String> 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<String, String> 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<String, String> 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<String, String> multifileUploadAssist(HttpServletRequest request, String basePath, String exclude) throws IOException {
    exclude = exclude == null ? "" : exclude;

Map<String, String> filePaths = new HashMap<String, String>();
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<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
List<MultipartFile> 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;
}




猜你喜欢

转载自www.cnblogs.com/drawStart/p/12522129.html