SpringMVC上傳多個圖片
阿新 • • 發佈:2018-11-14
匯入包:<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"; } } }