@RequestMapping(value = "/files.action") public String files( @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(); } model.addAttribute("imageFileName", fileName); return "page/savefile"; }如何使参数image和image1有一样的效果
时间: 2023-06-14 12:07:35 浏览: 121
可以将@RequestParam(value ="image", required = false) MultipartFile file和@RequestParam(value ="image1", required = false) MultipartFile file1合并成一个@RequestParam(value ="file", required = false) MultipartFile[] files,然后在方法内部通过循环处理每一个文件。修改后的代码如下:
@RequestMapping(value = "/files.action")
public String files(@RequestParam(value ="file", required = false) MultipartFile[] files, HttpServletRequest request, ModelMap model) {
String path = request.getSession().getServletContext().getRealPath("/") + "upfiles/";
List<String> fileNames = new ArrayList<String>();
for(MultipartFile file: files){
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();
}
fileNames.add(fileName);
}
model.addAttribute("imageFileNames", fileNames);
return "page/savefile";
}
阅读全文