首先引入兩個js
1 <script type="text/javascript" src="${pageContext.request.contextPath }/resource/js/jquery-1.8.3.js"></script> 2 <script type="text/javascript" src="${pageContext.request.contextPath }/resource/js/jquery_ocupload.js"></script>
1 <body> 2 <button type="button" id="import">上傳文件</button> 3 </body>
1 <script type="text/javascript"> 2 $("#import").upload({ 3 name : 'upload', // 文件名,要與ation中的參數名一致 4 action : '${pageContext.request.contextPath}/upload/file.do', // action路徑 5 enctye : 'multipart/form-data', // 設置編碼格式,默認multipart/form-data 6 autoSubmit : true, // 選中文件提交表單 7 onComplete : function(flag) { // 請求完成后的回調函數 8 if (flag == '0') { 9 alert("數據導入成功!"); 10 } else { 11 alert("數據導入失敗!"); 12 } 13 } 14 }); 15 </script>
后台代碼:
1 @RequestMapping(method=RequestMethod.POST, value="/upload/file") 2 @ResponseBody 3 private String upload(MultipartFile upload, HttpServletRequest request) throws IOException { 4 String flag = ""; 5 String path = request.getRealPath("/") + "../dexing/politik"; // 存放文件的路徑 6 File file = new File(path, upload.getOriginalFilename()); 7 if (file.exists()) { // 判斷文件是否已經存在 8 flag = "1"; 9 return flag; 10 } else { 11 try { 12 upload.transferTo(file); // 將文件寫到指定路徑下 13 } catch (Exception e) { 14 flag = "-1"; 15 e.printStackTrace(); 16 return flag; 17 } 18 } 19 flag = "0"; 20 return flag; 21 }