说明
1.前端上传文件必须用表单上传
/**
* 上传图片
*
* @param params
* @return
*/
@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> handleFileUpload(@RequestParam("file") CommonsMultipartFile file) {
Map<String, Object> result = new HashMap<String, Object>();
if (file == null) {
result.put("code", 0);
result.put("message", "文件不能为空");
result.put("data", new HashMap<>());
}
FileItem item = file.getFileItem();
String fileName = "";
String fileSuffix = "";
if (!item.isFormField()) {
String name = item.getName();
if (StringUtils.isNotEmpty(name)) {
fileSuffix = name.substring(name.lastIndexOf(".") + 1, name.length());//获取文件后缀名
fileName = CodeGenerator.getUUID() + "." + fileSuffix;//文件重命名,防止重复文件
}
}
String bathPath = SysConfig.getPropertiesByKey("uploadPath");//硬盘上的路径
String currentPath = "/image/" + CommonUtil.getUserId();
String path = bathPath + currentPath;
File dest = new File(bathPath + currentPath);
if (!dest.exists()) {//目录不存在,创建目录
dest.mkdirs();
}
System.out.println(path + fileName);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(dest, fileName)));
stream.write(bytes);
stream.close();
result.put("code", 1);
result.put("message", "success");
result.put("data", currentPath + "/" + fileName);
} catch (Exception e) {
result.put("code", 0);
result.put("message", e.toString());
System.out.println(e.toString());
result.put("data", new HashMap<>());
}
} else {
result.put("code", 0);
result.put("message", "文件不能为空");
System.out.println("文件不能为空");
result.put("data", new HashMap<>());
}
return result;
}