springMvc3+extjs4的上传与下载
最近生活过的很充实,人一直在不停的忙碌着学习新东西。这是我最近遇到的问题,我找度娘n了很久,终于找到了解决方案!
前台代码:
1 <script> 2 Ext.onReady(function() { 3 4 Ext.create('Ext.form.Panel', { 5 title : '文件上传', 6 width : 400, 7 bodyPadding : 10, 8 frame : true, 9 renderTo : document.body, 10 items : [ { 11 xtype : 'filefield', 12 name : '文件', 13 fieldLabel : 'File', 14 labelWidth : 50, 15 msgTarget : 'side', 16 allowBlank : false, 17 anchor : '100%', 18 buttonText : '请选择文件...' 19 } ], 20 21 buttons : [ { 22 text : '上传', 23 handler : function() { 24 var form = this.up('form').getForm(); 25 if (form.isValid()) { 26 form.submit({ 27 url : '根路径/fileUploadDown/fileUpload', 28 waitMsg : '正在上传文件中...', 29 success : function(fp, o) { 30 Ext.Msg.alert('上传文件成功!'); 31 } 32 }); 33 } 34 } 35 } ] 36 }); 37 38 }); 39 </script>
后台代码:
1 /** 2 *记录返回结果*/ 3 class ExtJSFormResult { 4 5 private boolean success; 6 7 public boolean isSuccess() { 8 return success; 9 } 10 11 public void setSuccess(boolean success) { 12 13 } 14 15 public String toString() { 16 return "{success:" + this.success + "}"; 17 } 18 } 19 20 21 class FileUploadBean { 22 23 private CommonsMultipartFile file; 24 25 public CommonsMultipartFile getFile() { 26 return file; 27 } 28 29 public void setFile(CommonsMultipartFile file) { 30 this.file = file; 31 } 32 } 33 34 /** 35 * 文件的上传与下载 36 * @author Administrator 37 * 38 */ 39 @Controller 40 @RequestMapping(value = "/fileUploadDown") 41 public class FileUploadAndDownController { 42 43 private static int countter=1; //定义一个计数器,用于上传文件的重命名 44 45 @Autowired 46 private ProAnnexDao<ProAnnex> proAnnextDao; 47 48 49 50 public void setProAnnextDao(ProAnnexDao<ProAnnex> proAnnextDao) { 51 this.proAnnextDao = proAnnextDao; 52 } 53 54 @RequestMapping(value="fileUpload",method = RequestMethod.POST) 55 public @ResponseBody String create(RedirectAttributes redirectAttributes,FileUploadBean uploadItem, 56 BindingResult result,HttpSession session){ 57 //获取根路径 58 String uploadFolderPath = session.getServletContext().getRealPath("/"); 59 ExtJSFormResult extjsFormResult = new ExtJSFormResult(); 60 try { 61 62 if (result.hasErrors()) { 63 for (ObjectError error : result.getAllErrors()) { 64 System.err.println("Error: " + error.getCode() + " - " 65 + error.getDefaultMessage()); 66 } 67 68 // 设置ExtJS返回 - error 69 extjsFormResult.setSuccess(false); 70 71 return extjsFormResult.toString(); 72 } 73 74 MultipartFile file = uploadItem.getFile(); 75 String fileName = null; 76 InputStream inputStream = null; 77 OutputStream outputStream = null; 78 if(file.getSize()>0){ 79 System.out.println("File Size:::" + file.getSize()); 80 if(file.getSize()>5242880){ 81 System.out.println("File Size:::" + file.getSize()); 82 extjsFormResult.setSuccess(false); 83 return "error"; 84 } 85 86 inputStream = file.getInputStream(); 87 88 File newFile = new File(uploadFolderPath + "fileUpload/"); 89 //如果文件路径不存在就新建一个 90 if(!newFile.exists()){ 91 newFile.mkdirs(); 92 } 93 //获取文件名 94 String name=file.getOriginalFilename(); 95 //从数据库中查询存在此类文件名否 96 Long count=proAnnextDao.isRepeatName(name); 97 //如果存在一样的文件名,就进行从命名 98 if (count>0) { 99 name=name.substring(0, name.lastIndexOf("."))+"("+(countter++)+")"+name.substring(name.lastIndexOf(".")); 100 } 101 102 fileName = uploadFolderPath + "fileUpload/" + name; 103 outputStream = new FileOutputStream(fileName); 104 int readBytes = 0; 105 byte[] buffer = new byte[10000]; 106 while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) { 107 outputStream.write(buffer, 0, readBytes); 108 } 109 110 outputStream.close(); 111 inputStream.close(); 112 113 114 } 115 116 // 设置ExtJS返回 - sucsess 117 extjsFormResult.setSuccess(true); 118 } catch (Exception e) { 119 120 e.printStackTrace(); 121 // 设置ExtJS返回 - error 122 123 extjsFormResult.setSuccess(false); 124 } 125 126 127 return extjsFormResult.toString(); 128 } 129 130 131 }
springMvc.xml(此文件名可能跟项目的实际情况有区别)中的配置:
1 2 <!-- 上传文件,限制大小的配置 --> 3 <bean id="multipartResolver" 4 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 5 <!--resolveLazily属性启用是为了推迟文件解析,以便在Upload中捕获文件大小异常--> 6 <property name="resolveLazily" value="true"/> 7 <property name="maxUploadSize" value="5242880" /> 8 </bean> 9 10 11 <!-- 将无法mapping到Controller的path交给default servlet handler处理 --> 12 <mvc:default-servlet-handler/><!-- 使用默认的servlet来响应静态文件 --> 13 <!-- 文件的上传与下载 --> 14 <mvc:view-controller path="/" view-name="redirect:/fileUploadDown"/>
以上的就是上传文件了。
那下载呢?
下载比较简单,代码如下:
1 @RequestMapping("/downloadFile") 2 public void download(@Valid @ModelAttribute("downLoadName") String downLoadName, 3 HttpServletResponse response,HttpSession session,BindingResult result,HttpServletRequest request) throws IOException { 4 5 response.setCharacterEncoding("UTF-8"); 6 request.setCharacterEncoding("UTF-8"); 7 //获取文件的路径 8 String url=session.getServletContext().getRealPath("/")+"/fileUpload/"+downLoadName; 9 System.out.println(url); 10 File file=new File(url); 11 12 InputStream input = FileUtils.openInputStream(file); 13 byte[] data = IOUtils.toByteArray(input); 14 15 //System.out.println("文件名:"+downLoadName); 16 response.reset(); 17 //设置响应的报头信息(中文问题解决办法) 18 response.setHeader("content-disposition","attachment;fileName="+URLEncoder.encode(downLoadName, "UTF-8")); 19 response.addHeader("Content-Length", "" + data.length); 20 response.setContentType("application/octet-stream; charset=UTF-8"); 21 22 IOUtils.write(data, response.getOutputStream()); 23 IOUtils.closeQuietly(input); 24 25 }
在界面上只要有一个连接地址:如:window.location.href="根路径/fileUploadDown/downfile/downLoadName="+name;这样就可以下载了.... 超连接的写法基本一样,这里就不多说了.