照片上传时给重命名时使用UUID进行重命名。
在实现方法上传的方法中调用工具类的地方
Map<String, Object> result = ImageUtil.getInstance().uploadImgByUuid(Constants.UPLOAD_IMG_COMMENTFILE, imgFile);图片上传工具类中的方法:
public class ImageUtil { private static ImageUtil instance; /** * 定义私有构造方法实现单例 */ public ImageUtil() { super(); } public synchronized static ImageUtil getInstance() { if(instance == null) { instance = new ImageUtil(); } return instance; } public Map<String,Object> uploadImgByUuid(String dir,MultipartFile file) { Map<String,Object> jsonResult = new HashMap<String, Object>(); String msg = ""; try { String fileName = file.getOriginalFilename(); long fileSize = file.getSize(); String exts = fileName.substring(fileName.lastIndexOf(".") + 1); if (fileSize > ResourceUtil.getUploadImageMaxSize()) { msg = "上传图片应小于2MB!"; jsonResult = JsonResult.jsonWsReturn(1, msg ,false); LogService.getInstance(this).info("『功能:存储图片』失败 ,msg:" + msg); return jsonResult; } if (exts.indexOf(ResourceUtil.getUploadImageExts()) != -1) { msg = "上传格式应属于:" + ResourceUtil.getUploadImageExts(); jsonResult = JsonResult.jsonWsReturn(1, msg ,false); LogService.getInstance(this).info("『功能:存储图片』 ,msg:" + msg); return jsonResult; } //图片命名规则:uuid命名方式 fileName =UUID.randomUUID().toString()+"."+exts; String path = dir + File.separator + fileName; //删除原文件 //防止误传地址误删信息 // 存储路径 String dirPath = ResourceUtil.getUploadImageRelativeRoot2()+ dir; String filePath = ResourceUtil.getUploadImageRelativeRoot2() + path; LogService.getInstance(this).debug(filePath); boolean resultDir = FileUtil.makedir(dirPath); if (resultDir == true) { File targetFile = new File(filePath); file.transferTo(targetFile); jsonResult = JsonResult.jsonWsReturn(0,fileName ,true); LogService.getInstance(this).info("『功能:储存图片』: ,fileName:" + fileName + " ,msg:" + msg); } else { msg = "建立文件夹" + dirPath + "失败!"; jsonResult = JsonResult.jsonWsReturn(1, msg ,false); LogService.getInstance(this).error("建立文件夹" + dirPath + "失败,完整路径为:dirPath"); } } catch (Exception e) { msg = "上传图片失败!"; jsonResult = JsonResult.jsonWsReturn(1, msg ,false); LogService.getInstance(this).error("上传图片失败",e); } return jsonResult; } }