MultipartFile上传文件
@RequestMapping("/addAppVersion")
public String addAppVersion(@RequestParam(value = "apkFile", required = false) MultipartFile file, AppVersion appVersion, int appInfoId, Model model, HttpSession session, HttpServletRequest request) {
String PicPath = null;
File targetFile = null;
String fileName = null;
if (!file.isEmpty()) {
String path = session.getServletContext().getRealPath(request.getContextPath() + "/static/" + "uploadfiles");
String originalFilename = file.getOriginalFilename();
String suffix = FilenameUtils.getExtension(originalFilename);
int fileSize = 512000000;
if (file.getSize() > fileSize) {
model.addAttribute("errorMessage", "上传文件大小不得超过500MB");
return "redirect:/appInfo/toAddAppVersion";
}
else if (suffix.equalsIgnoreCase("apk")) {
Random random = new Random();
fileName = "com." + System.currentTimeMillis() + random.nextInt(1000000) + "APP.apk";
targetFile = new File(path, fileName);
if (!targetFile.exists()) targetFile.mkdirs();
try {
file.transferTo(targetFile);
} catch (IOException e) {
model.addAttribute("errorMessage", "上传文件失败!");
e.printStackTrace();
return "redirect:/appInfo/toAddAppVersion";
}
PicPath = path + "/" + fileName;
} else {
model.addAttribute("errorMessage", "上传文件格式不正确!");
return "redirect:/appInfo/toAddAppVersion";
}
}
DevUser devUser = (DevUser) session.getAttribute(Constants.DEV_SESSION);
appVersion.setCreatedBy(devUser.getId());
Date date = new Date();
appVersion.setCreationDate(date);
if (fileName != null) {
appVersion.setDownloadLink(request.getContextPath() + "/static/" + "uploadfiles/" + fileName);
appVersion.setApkLocPath(PicPath);
appVersion.setApkFileName(fileName);
}
int i = appVersionService.AddAppVersion(appVersion);
if (i < 1) {
model.addAttribute("message", "添加版本失败!");
return "redirect:/appInfo/toAddAppVersion";
}
int id = appVersion.getId();
AppInfo appInfo = appInfoService.selectAppInfoById(appInfoId);
appInfo.setVersionId(id);
return "forward:/appInfo/appList";
}