SpringMVC上传多个图片

导入包:<dependency>
      				<groupId>commons-fileupload</groupId>
     				 <artifactId>commons-fileupload</artifactId>
     				 <version>1.3.3</version>
   			 </dependency>

Spring.xml:配置MultipartResolver:用于处理表单中的file
在这里插入图片描述

jsp页面:
在这里插入图片描述

file类:`@Controller
public class file {
        @Autowired
        ServletContext context;
        @RequestMapping("fileUploadPage")
        public String fileUploadPage(@RequestParam(value="uploadFile") MultipartFile[] file, Model model, HttpServletRequest request) throws Exception {
            //判断文件是否为空
            if(file.length!=0){
                for (MultipartFile s:file) {
                //获得原文件名
                String fileName = s.getOriginalFilename();
                //File.separator表示在 UNIX 系统上,此字段的值为 /;在 Windows 系统上,它为 \,如:C:\tmp\test.txt和tmp/test.txt
                String filePath = "D:\\"+s.getOriginalFilename();
                //获得当前日期
                Calendar ca = Calendar.getInstance();
                //拼接日期文件夹
                filePath += "" + ca.get(ca.YEAR) + (ca.get(ca.MONTH)+1) + ca.get(ca.DATE);
                File dateDir = new File(filePath);
                //判断当前日期文件夹是否存在,不存在创建
                if(!dateDir.exists()){
                    dateDir.mkdirs();
                }
                //文件名由客户端IP地址+系统当前毫秒数组成
                filePath += File.separator + request.getRemoteAddr().replace(":","") + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
                // 复制本地文件到服务器
                FileCopyUtils.copy(s.getBytes(), new File(filePath));
                // 将文件保存路径放到request作用域
                model.addAttribute("filePath", filePath);
                }
                return "success";
            }else{
                System.out.println("文件上传异常");
                return "input";
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_41251714/article/details/83344130