code
@RequestMapping("/uploadFile")
@ResponseBody
public AjaxResult uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return new AjaxResult(0, "isMultipart error");
}
String type = request.getParameter("type");
if (StrUtils.isEmpty(type)) {
return new AjaxResult(0, "type error");
}
boolean isOk = false;
String imgUrl = "";
try {
// FileItem 是表单中的每一个元素的封装 创建一个 FileItem 的工厂类
FileItemFactory factory = new DiskFileItemFactory();
// 创建一个文件上传处理器(装饰设计模式)
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析请求
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) {
continue;
}
String savePathDir = request.getServletContext().getRealPath("/upload/" + getExId(request) + "/" + type + "/");
File file = new File(savePathDir);
if (!file.exists()) file.mkdir();
String fileName = UUID.randomUUID() + fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
fileItem.write(new File(savePathDir + fileName));
imgUrl = request.getContextPath() + "/upload/" + getExId(request) + "/" + type + "/" + fileName;
isOk = true;
break;
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
return AjaxResult.fail();
}
AjaxResult ajaxResult = AjaxResult.success();
if (isOk) {
ajaxResult.getMap().put("filename", imgUrl);
} else {
ajaxResult.setCode(0);
ajaxResult.setMsg("上传失败");
File file = new File(imgUrl);
if (file.exists()) {
file.delete();
}
}
return ajaxResult;
}