@RequestMapping(value = "/image.action") public String upload( @RequestParam(value ="image", required = false) MultipartFile file, @RequestParam(value ="image1", required = false) MultipartFile file1, HttpServletRequest request, ModelMap model) { String path = request.getSession().getServletContext().getRealPath("/") + "upfiles/"; String fileName = file.getOriginalFilename(); int i = fileName.lastIndexOf("."); String name = String.valueOf(VeDate.getStringDatex()); String type = fileName.substring(i + 1); fileName = name + "." + type; File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } // 保存第一张图片 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } // 保存第二张图片 String fileName1 = file1.getOriginalFilename(); int j = fileName1.lastIndexOf("."); String name1 = String.valueOf(VeDate.getStringDatex()); String type1 = fileName1.substring(j + 1); fileName1 = name1 + "." + type1; File targetFile1 = new File(path, fileName1); if (!targetFile1.exists()) { targetFile1.mkdirs(); } try { file1.transferTo(targetFile1); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("imageFileName", fileName); model.addAttribute("image1FileName", fileName1); return "page/saveimage"; }如何添加判断空指针异常的代码
时间: 2023-06-15 13:07:23 浏览: 101
简单捋捋@RequestParam 和 @RequestBody的使用
5星 · 资源好评率100%
可以在上传文件之前,先判断文件是否为 null,如果为 null 就抛出空指针异常。可以像下面这样修改代码:
@RequestMapping(value = "/image.action")
public String upload(@RequestParam(value ="image", required = false) MultipartFile file,
@RequestParam(value ="image1", required = false) MultipartFile file1,
HttpServletRequest request, ModelMap model) {
String path = request.getSession().getServletContext().getRealPath("/") + "upfiles/";
// 判断第一张图片是否为空
if (file == null) {
throw new NullPointerException("第一张图片不能为空!");
}
String fileName = file.getOriginalFilename();
int i = fileName.lastIndexOf(".");
String name = String.valueOf(VeDate.getStringDatex());
String type = fileName.substring(i + 1);
fileName = name + "." + type;
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存第一张图片
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
// 判断第二张图片是否为空
if (file1 == null) {
throw new NullPointerException("第二张图片不能为空!");
}
String fileName1 = file1.getOriginalFilename();
int j = fileName1.lastIndexOf(".");
String name1 = String.valueOf(VeDate.getStringDatex());
String type1 = fileName1.substring(j + 1);
fileName1 = name1 + "." + type1;
File targetFile1 = new File(path, fileName1);
if (!targetFile1.exists()) {
targetFile1.mkdirs();
}
// 保存第二张图片
try {
file1.transferTo(targetFile1);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("imageFileName", fileName);
model.addAttribute("image1FileName", fileName1);
return "page/saveimage";
}
阅读全文