首先引入两个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 }