悠然哈哈哈

导航

ExtJS+SpringMVC文件上传与下载

说到文件上传、下载功能,网络上大多介绍的是采用JSP、SpringMVC或者Struts等开源框架的功能,通过配置达到文件上传、下载的目地。可是最近项目要用到文件上传与下载的功能,因为本项目框架采用开源框架SpringMVC、ExtJS、Hibernate写成的,当然借助SpringMVC框架本身的文件上传与下载也可以,但是同样需要和以前一样,编写一些配置文件,所以最近自己搞了一下关于ExtJS、SpringMVC的免配置文件上传与下载的功能研究。

        提起文件上传,免不了客户端(提交文件)和服务器端(接收文件)的结合。

        首先定义全局相关变量:

  1. /** 
  2.  * @author:limingzhong 
  3.  * @desc:定义相关全局静态变量 
  4.  * @Date:2012-02-28 
  5.  */  
  6. private final static String UPLOAD_SUCCESS = "{success:true,mess:'文件上传成功!'}";  
  7.   
  8. private final static String UPLOAD_FAILURE = "{success:false,mess:'文件上传失败!'}";  
  9.   
  10. private final static String FILE_NO = "{success:false,mess:'文件不存在!'}";  
  11.   
  12. private final static String FILE_YES = "{success:true,mess:'文件存在!'}";  
  13.   
  14. private final static String CONTENT_TYPE = "text/html;charset=gb2312";  
  15.   
  16. private final static String APPLICATION = "application/octet-stream";  

        客户端:采用ExtJS的formPanel提交功能

[javascript] view plaincopyprint?在CODE上查看代码片派生到我的代码片
 
  1. var excelUpload = new Ext.form.TextField({     
  2.     id:'excelUpload',   
  3.     anchor:'90%',     
  4.     height:30,  
  5.     width:350,    
  6.     name:'file',  
  7.     inputType:'file',  
  8.     fieldLabel:'文件选择'  
  9. });  
  10.           
  11. var formPanel = new Ext.form.FormPanel({  
  12.     labelWidth:80,  
  13.     bodyStyle:'padding:5 5 5 5',  
  14.     height:515,  
  15.     width:200,  
  16.     frame:true,  
  17.     fileUpload:true,  
  18.     items:[excelUpload]  
  19. });  
  20.   
  21. // 定义按钮  
  22. var upLoadFile = new Ext.Toolbar.Button({  
  23.     text:'上传'  
  24. });  
  25.   
  26. // 下载数据功能  
  27. var up = function(bt) {  
  28.     var excelName = Ext.getCmp('excelUpload').getRawValue();// 上传文件名称的路径  
  29.     if (excelName == ""){  
  30.         Ext.Msg.show({title:'提示',msg:'请选择文件!',buttons:Ext.Msg.OK,icon:Ext.MessageBox.INFOR});  
  31.         return;  
  32.     }else {  
  33.         var array = new Array();  
  34.         array = excelName.split("\\");  
  35.         var length = array.length;  
  36.         var fileName = "";  
  37.         var index = 0;  
  38.         for (index = 0; index < length; index++) {  
  39.             if (fileName == "") {  
  40.                 fileName = array[index];  
  41.             } else {  
  42.                 fileName = fileName + "/" + array[index];  
  43.             }  
  44.         }  
  45.           
  46.         formPanel.getForm().submit({  
  47.             url:'http://localhost:8080/pro/upload.json',  
  48.             method:'POST',  
  49.             waitMsg:'数据上传中, 请稍等...',  
  50.             success:function(form, action, o) {  
  51.                 Ext.MessageBox.alert("提示信息",action.result.mess);  
  52.             },  
  53.             failure : function(form, action) {  
  54.                 Ext.MessageBox.alert("提示信息","请求失败,文件上传失败");  
  55.             }  
  56.         });  
  57.     }  
  58. }  
  59.       
  60. // 添加按钮的响应事件  
  61. upLoadFile.addListener('click', up, false);  
  62.       
  63. var window = new Ext.Window({  
  64.     title:'上传文件',  
  65.     width:500,  
  66.     height:200,  
  67.     minWidth:500,  
  68.     minHeight:200,  
  69.     layout:'fit',  
  70.     plain:true,  
  71.     modal:true,  
  72.     //closeAction:'hide',  
  73.     bodyStyle:'padding:5px;',  
  74.     buttonAlign:'center',  
  75.     items:formPanel,  
  76.     buttons:[upLoadFile]  
  77. });  
  78. window.show();  

ss

       服务器端:根据SpringMVC注解直接调用对应方法,采用流的形式上传文件,这样直接避免配置xml等文件的麻烦。

  1. /** 
  2.  * @author:limingzhong 
  3.  * @throws:IOException  
  4.  * @desc:上传文件 
  5.  * @params:自带参数,客户端不传入实参 
  6.  * @Date:2012-02-28 
  7.  */  
  8. @RequestMapping(value = "/upload.json")   
  9. public void upLoad(HttpServletRequest request,HttpServletResponse response) throws IOException {  
  10.       
  11.     response.setContentType(CONTENT_TYPE);  
  12.     PrintWriter out = response.getWriter();  
  13.       
  14.     if (!ServletFileUpload.isMultipartContent(request)){  
  15.         out.println(UPLOAD_FAILURE);  
  16.     }  
  17.       
  18.     String name = null;  
  19.     try {  
  20.         DiskFileItemFactory factory = new DiskFileItemFactory();  
  21.         factory.setSizeThreshold(4096);  
  22.         ServletFileUpload upload = new ServletFileUpload(factory);  
  23.         upload.setSizeMax(4 * 1024 * 1024);  
  24.         Iterator<?> iter = upload.parseRequest(request).iterator();  
  25.         while (iter.hasNext()) {  
  26.             FileItem item = (FileItem) iter.next();  
  27.             if (item.isFormField()) {  
  28.                 name = item.getFieldName();  
  29.                 out.println(UPLOAD_FAILURE);  
  30.             } else {  
  31.                 name = item.getName();  
  32.                 String path = getPath();  
  33.                 if(path==null || path==""){  
  34.                     out.println(UPLOAD_FAILURE);  
  35.                 }else{  
  36.                     item.write(new File(path+name.substring(name.lastIndexOf(File.separator)+1,name.length()))); //保存上传文件  
  37.                     out.println(UPLOAD_SUCCESS);  
  38.                 }  
  39.             }  
  40.         }  
  41.         out.close();  
  42.     } catch (Exception e) {  
  43.         out.println(UPLOAD_FAILURE);  
  44.         out.close();  
  45.     }  
  46. }  

       至此,文件上传的功能已结束。

       下面把下载功能的客户端和服务器端的代码贴出来,以供大家拍砖:

       客户端:

[javascript] view plaincopyprint?在CODE上查看代码片派生到我的代码片
 
  1. window.location.href = 'http://127.0.0.1:8080/pro/down.json?fileName='+encodeURI(encodeURI(fileName));  

       服务器端:

  1. /** 
  2.  * @author:limingzhong 
  3.  * @throws:IOException  
  4.  * @desc:下载文件 
  5.  * @params:fileName-文件名称 
  6.  * @Date:2012-02-28 
  7.  */  
  8. @RequestMapping(value = "/down.json")   
  9. public void down(@RequestParam("fileName") String fileName,HttpServletRequest request,HttpServletResponse response) throws IOException {  
  10.     response.setContentType(APPLICATION);  
  11.     fileName = URLDecoder.decode(fileName, "utf-8");  
  12.     String path = getPath()+fileName;  
  13.     path = path.replace("%20", " ");  
  14.     File file = new File(path);  
  15.       
  16.     // 清空response  
  17.        response.reset();  
  18.          
  19.        // 设置response的Header  
  20.        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"iso8859-1"));  
  21.        response.addHeader("Content-Length", "" + file.length());  
  22.          
  23.     try{  
  24.         //以流的形式下载文件  
  25.         InputStream fis = new BufferedInputStream(new FileInputStream(path));  
  26.         byte[] buffer = new byte[fis.available()];  
  27.         fis.read(buffer);  
  28.         fis.close();  
  29.           
  30.         OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
  31.         toClient.write(buffer);  
  32.         toClient.flush();  
  33.         toClient.close();  
  34.     }catch(Exception e){  
  35.         e.printStackTrace();  
  36.     }  
  37. }  

      至此,文件下载的功能已结束。

 

 

来自:http://blog.csdn.net/limingzhong198/article/details/7324570

posted on 2015-04-27 09:33  悠然886  阅读(556)  评论(0编辑  收藏  举报