@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 16:06:40 浏览: 77
在上传第一张图片时,代码并没有判断第二张图片是否为空,所以当第二张图片为空时,会导致 `file1` 变量为空,从而导致空指针异常错误。为了解决这个问题,你可以在上传第二张图片之前,先判断一下第二张图片是否为空,如果为空,则跳过第二张图片的上传操作。你可以尝试修改代码如下:
```
@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();
}
// 判断第二张图片是否为空
if (file1 != null && !file1.isEmpty()) {
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("image1FileName", fileName1);
}
model.addAttribute("imageFileName", fileName);
return "page/saveimage";
}
```
阅读全文