flex+java上传

在研究Flex DataGrid导入excel时,用到了Flex的文件上传功能。 (参见我的Blog:http://cwfmaker.javaeye.com/blog/539449) 在Adobe的Flex RIA编程环境下,是无法读取本地文件的(据我所知),但是我们可以依赖于Flex调用后台的代码实现文件上传功能,我这里是利用Flex的URLRequest来向java的Servlet传送一个Http请求(Servlet集成自HttpServlet ,已实现文件上传功能),而Servlet响应请求之后会利用Apcahe的开源Jar包(org.apache.commons.fileupload.servlet.ServletFileUpload类)完成文件的生成。 通过以上原理就可以利用Flex+java实现文件上传。(这里也是参考了网上的一些文章)

 

   java Servlet 代码

Java代码 复制代码
  1. package com.yyhy.java.util;   
  2.   
  3. //多文件上传的Java端的类   
  4. import javax.servlet.http.HttpServlet;   
  5. import javax.servlet.http.HttpServletRequest;   
  6. import javax.servlet.http.HttpServletResponse;   
  7. import javax.servlet.ServletException;   
  8. import java.util.List;   
  9. import java.util.Iterator;   
  10. import java.io.File;   
  11. import java.io.IOException;   
  12. import java.io.UnsupportedEncodingException;   
  13. import java.net.URLDecoder;   
  14. import org.apache.commons.fileupload.FileUploadException;   
  15. import org.apache.commons.fileupload.disk.DiskFileItemFactory;   
  16. import org.apache.commons.fileupload.servlet.ServletFileUpload;   
  17. import org.apache.commons.fileupload.FileItem;   
  18. import org.apache.log4j.Logger;   
  19. import org.apache.commons.lang.ObjectUtils;   
  20. import org.springframework.context.ApplicationContext;   
  21. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  22.   
  23.   
  24. public class FileUploadAction extends HttpServlet {   
  25.   
  26.     // 限制文件的上传大小   
  27.     private int maxPostSize = 100 * 1024 * 1024;   
  28.     //文件上传地址   
  29.     private String uploadPath;   
  30.   
  31.     public FileUploadAction() {   
  32.         //从配置文件中取得文件上传地址   
  33.         setUploadPath();   
  34.     }   
  35.     public String getUploadPath() {   
  36.         return uploadPath;   
  37.     }   
  38.     public void setUploadPath() {   
  39.         //从配置文件中取得文件上传地址   
  40.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");   
  41.         ServerAddress serverAddressBean=(ServerAddress)context.getBean("ServerAddressBean");   
  42.         this.uploadPath = serverAddressBean.getUploadPath().trim();   
  43.     }      
  44.     // 文件上传   
  45.     public void service(HttpServletRequest request, HttpServletResponse response)   
  46.             throws ServletException   
  47.             {   
  48.             this.doUploadAdd(request, response);   
  49.     }   
  50.        
  51.     private void logger(String info) {   
  52.         System.out.println(info);   
  53.     }   
  54.        
  55.     protected void doGet(HttpServletRequest request, HttpServletResponse response)      
  56.     throws ServletException, IOException {      
  57.         doUploadAdd(request, response);      
  58.      }   
  59.        
  60.     protected void doPost(HttpServletRequest request, HttpServletResponse response)      
  61.     throws ServletException, IOException {      
  62.         doUploadAdd(request, response);      
  63.      }   
  64.        
  65.     private void doUploadAdd(HttpServletRequest request,   
  66.             HttpServletResponse response) throws ServletException {   
  67.         logger("begin to upload");   
  68.         try {   
  69.             request.setCharacterEncoding("UTF-8");// 防止文件名称带有汉字后传到服务器乱码        
  70.             //建立文件夹   
  71.             this.makeDir(uploadPath);   
  72.         } catch (UnsupportedEncodingException e) {   
  73.             // TODO Auto-generated catch block   
  74.             e.printStackTrace();   
  75.         }   
  76.         saveFiletoServer(request,response,uploadPath);   
  77.     }   
  78.        
  79.     private void doUploadDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException    
  80.     {   
  81.         String dirtyStr = "";//需要删除的文件名(单个文件)或文件夹名列表   
  82.         try    
  83.         {   
  84.             if (request.getParameter("dirtyStr") != null) {   
  85.                 dirtyStr=URLDecoder.decode(request.getParameter("dirtyStr"),"utf-8");//前台ENCODE,后台DECODE   
  86.                 logger("删除的文件(夹)为:" + dirtyStr);   
  87.             }   
  88.         }   
  89.         catch (Exception e) {   
  90.             // TODO Auto-generated catch block   
  91.             logger(e.getMessage());   
  92.         }   
  93.   
  94.         try {   
  95.             new DeleteFiles().DeleteModifyFiles(dirtyStr, uploadPath);   
  96.         } catch (Exception e) {   
  97.             logger(e.getMessage());   
  98.         }   
  99.     }   
  100.     //保存文件到服务器中   
  101.     private void saveFiletoServer(HttpServletRequest request,HttpServletResponse response,String uploadPath)   
  102.     {   
  103.         // 操作文件   
  104.         response.setContentType("text/html; charset=UTF-8");   
  105.         DiskFileItemFactory factory = new DiskFileItemFactory();   
  106.         factory.setSizeThreshold(1024 * 4);   
  107.         ServletFileUpload upload = new ServletFileUpload(factory);   
  108.         upload.setFileSizeMax(maxPostSize);   
  109.         logger("request========" + ObjectUtils.toString(request));   
  110.         List fileItems = null;   
  111.         try {   
  112.             fileItems = upload.parseRequest(request);   
  113.             logger("============" + ObjectUtils.toString(fileItems));   
  114.             Iterator iter = fileItems.iterator();   
  115.             while (iter.hasNext()) {   
  116.                 FileItem item = (FileItem) iter.next();   
  117.                 log(item.toString());   
  118.                 if (!item.isFormField()) {   
  119.                     String name = item.getName();   
  120.                     logger("上传的文件名 = " + name);   
  121.                     try {   
  122.                         item.write(new File(uploadPath + name));   
  123.                     } catch (Exception ex) {   
  124.                         logger(ex.getMessage());   
  125.                     }   
  126.                 }   
  127.             }   
  128.         } catch (FileUploadException ex1) {   
  129.             logger("FileUploadException->" + ex1.getMessage());   
  130.         }   
  131.     }   
  132.     // 建立文件夹路径   
  133.     private boolean makeDir(String uploadPath) {   
  134.         boolean isOK = false;   
  135.         try {   
  136.             File file = new File(uploadPath);   
  137.             file.mkdirs();   
  138.             isOK = true;   
  139.         } catch (Exception e) {   
  140.             isOK = false;   
  141.         } finally {   
  142.             return isOK;   
  143.         }   
  144.     }   
  145.     // 建立文件夹路径   
  146.     private boolean makeDirs(String uploadPath, String newDocStr) {   
  147.         boolean isOK = false;   
  148.         File file;   
  149.         String[] temp;   
  150.         try {   
  151.             temp = newDocStr.split(",");   
  152.             for (int i = 0; i < temp.length; i++) {   
  153.                 file = new File(uploadPath + temp[i] + "\\");   
  154.                 file.mkdirs();   
  155.             }   
  156.             isOK = true;   
  157.         } catch (Exception e) {   
  158.             isOK = false;   
  159.         } finally {   
  160.             return isOK;   
  161.         }   
  162.     }   
  163. }  
package com.yyhy.java.util;    //多文件上传的Java端的类  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import javax.servlet.ServletException;  import java.util.List;  import java.util.Iterator;  import java.io.File;  import java.io.IOException;  import java.io.UnsupportedEncodingException;  import java.net.URLDecoder;  import org.apache.commons.fileupload.FileUploadException;  import org.apache.commons.fileupload.disk.DiskFileItemFactory;  import org.apache.commons.fileupload.servlet.ServletFileUpload;  import org.apache.commons.fileupload.FileItem;  import org.apache.log4j.Logger;  import org.apache.commons.lang.ObjectUtils;  import org.springframework.context.ApplicationContext;  import org.springframework.context.support.ClassPathXmlApplicationContext;      public class FileUploadAction extends HttpServlet {     // 限制文件的上传大小   private int maxPostSize = 100 * 1024 * 1024;   //文件上传地址   private String uploadPath;     public FileUploadAction() {    //从配置文件中取得文件上传地址    setUploadPath();   }   public String getUploadPath() {    return uploadPath;   }   public void setUploadPath() {    //从配置文件中取得文件上传地址    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");    ServerAddress serverAddressBean=(ServerAddress)context.getBean("ServerAddressBean");    this.uploadPath = serverAddressBean.getUploadPath().trim();   }    // 文件上传   public void service(HttpServletRequest request, HttpServletResponse response)     throws ServletException     {     this.doUploadAdd(request, response);   }      private void logger(String info) {    System.out.println(info);   }      protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {       doUploadAdd(request, response);          }      protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {       doUploadAdd(request, response);          }      private void doUploadAdd(HttpServletRequest request,     HttpServletResponse response) throws ServletException {    logger("begin to upload");    try {     request.setCharacterEncoding("UTF-8");// 防止文件名称带有汉字后传到服务器乱码       //建立文件夹     this.makeDir(uploadPath);    } catch (UnsupportedEncodingException e) {     // TODO Auto-generated catch block     e.printStackTrace();    }    saveFiletoServer(request,response,uploadPath);   }      private void doUploadDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException    {    String dirtyStr = "";//需要删除的文件名(单个文件)或文件夹名列表    try     {     if (request.getParameter("dirtyStr") != null) {      dirtyStr=URLDecoder.decode(request.getParameter("dirtyStr"),"utf-8");//前台ENCODE,后台DECODE      logger("删除的文件(夹)为:" + dirtyStr);     }    }    catch (Exception e) {     // TODO Auto-generated catch block     logger(e.getMessage());    }      try {     new DeleteFiles().DeleteModifyFiles(dirtyStr, uploadPath);    } catch (Exception e) {     logger(e.getMessage());    }   }   //保存文件到服务器中   private void saveFiletoServer(HttpServletRequest request,HttpServletResponse response,String uploadPath)   {    // 操作文件    response.setContentType("text/html; charset=UTF-8");    DiskFileItemFactory factory = new DiskFileItemFactory();    factory.setSizeThreshold(1024 * 4);    ServletFileUpload upload = new ServletFileUpload(factory);    upload.setFileSizeMax(maxPostSize);    logger("request========" + ObjectUtils.toString(request));    List fileItems = null;    try {     fileItems = upload.parseRequest(request);     logger("============" + ObjectUtils.toString(fileItems));     Iterator iter = fileItems.iterator();     while (iter.hasNext()) {      FileItem item = (FileItem) iter.next();      log(item.toString());      if (!item.isFormField()) {       String name = item.getName();       logger("上传的文件名 = " + name);       try {        item.write(new File(uploadPath + name));       } catch (Exception ex) {        logger(ex.getMessage());       }      }     }    } catch (FileUploadException ex1) {     logger("FileUploadException->" + ex1.getMessage());    }   }   // 建立文件夹路径   private boolean makeDir(String uploadPath) {    boolean isOK = false;    try {     File file = new File(uploadPath);     file.mkdirs();     isOK = true;    } catch (Exception e) {     isOK = false;    } finally {     return isOK;    }   }   // 建立文件夹路径   private boolean makeDirs(String uploadPath, String newDocStr) {    boolean isOK = false;    File file;    String[] temp;    try {     temp = newDocStr.split(",");     for (int i = 0; i < temp.length; i++) {      file = new File(uploadPath + temp[i] + "\\");      file.mkdirs();     }     isOK = true;    } catch (Exception e) {     isOK = false;    } finally {     return isOK;    }   }  }

   

 

    Flex前台代码:

Actionscript代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <mx:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"    
  3.                 xmlns:s="library://ns.adobe.com/flex/spark"    
  4.                 xmlns:mx="library://ns.adobe.com/flex/halo" layout="absolute" width="400" height="300"  
  5.                 creationComplete="CreationCompletedHandler()"  
  6.                 showCloseButton="true">   
  7.     <fx:Script>   
  8.         <![CDATA[   
  9.             import mx.controls.Alert;   
  10.             import mx.events.CloseEvent;   
  11.             import mx.managers.PopUpManager;   
  12.             import mx.utils.StringUtil;   
  13.                
  14.             [Bindable]   
  15.             private var _filename:String;   
  16.   
  17.             public function get filename():String   
  18.             {   
  19.                 return _filename;   
  20.             }   
  21.   
  22.             public function set filename(value:String):void   
  23.             {   
  24.                 _filename = value;   
  25.             }   
  26.   
  27.                
  28.             [Bindable]   
  29.             private var _file:FileReference=new FileReference();    
  30.   
  31.             public function get file():FileReference   
  32.             {   
  33.                 return _file;   
  34.             }   
  35.   
  36.             public function set file(value:FileReference):void   
  37.             {   
  38.                 _file = value;   
  39.             }   
  40.   
  41.   
  42.             [Bindable]   
  43.             private var _serveraddress:String;   
  44.   
  45.             public function get serveraddress():String   
  46.             {   
  47.                 return _serveraddress;   
  48.             }   
  49.   
  50.             public function set serveraddress(value:String):void   
  51.             {   
  52.                 _serveraddress = value;   
  53.             }   
  54.   
  55.             /**creationComplete完成之后调用,获取服务器地址,建立事件监听   
  56.              * @param null   
  57.              * @author 陈文锋 54cwf@163.com   
  58.              * @return void   
  59.              * */   
  60.             public function CreationCompletedHandler():void   
  61.             {      
  62.                 Security.allowDomain("*");   
  63.                 var urlLoader:URLLoader=new URLLoader(new URLRequest("assets/conf/ServerAddressConfig.xml"));   
  64.                 urlLoader.addEventListener(Event.COMPLETE,CompletedHandler);   
  65.                 this.addEventListener(Event.CLOSE,TitleWindowClose);   
  66.                 file.addEventListener(ProgressEvent.PROGRESS,progressHandler);   
  67.                 file.addEventListener(Event.SELECT,selectedHandler);   
  68.                 file.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);   
  69.             }   
  70.                
  71.             private function ioErrorHandler(e:IOErrorEvent):void   
  72.             {   
  73.                 Alert.show(e.toString());   
  74.             }   
  75.                
  76.             private function progressHandler(e:ProgressEvent):void   
  77.             {   
  78.                 lblProgress.text = " 已上传 " + e.bytesLoaded       
  79.                     + " 字节,共 " + e.bytesTotal + " 字节";      
  80.                 var proc: uint = e.bytesLoaded / e.bytesTotal * 100;      
  81.                 uploadbar.setProgress(proc, 100);      
  82.                 uploadbar.label= "当前进度: " + " " + proc + "%";    
  83.             }   
  84.                
  85.             /**Event事件监听处理函数,弹出上传提示窗口   
  86.              * @param e,Event类型事件参数   
  87.              * @author  54cwf@163.com   
  88.              * @return void   
  89.              * */   
  90.             private function selectedHandler(e:Event):void   
  91.             {   
  92.                 Alert.show("上传 " + file.name + " (共 "+Math.round(file.size/1024)+"KB)?",      
  93.                     "确认上传",      
  94.                     Alert.YES|Alert.NO,      
  95.                     null,      
  96.                     proceedWithUpload);   
  97.             }   
  98.                
  99.             /**CloseEvent事件监听处理函数,访问upload的servlet服务   
  100.              * @param e,Event类型事件参数   
  101.              * @author  54cwf@163.com   
  102.              * @return void   
  103.              * */   
  104.             private function proceedWithUpload(e:CloseEvent): void{      
  105.                 if (e.detail == Alert.YES)   
  106.                 {      
  107.                     filename=file.name;   
  108.                     var request:URLRequest = new URLRequest(StringUtil.trim(serveraddress));      
  109.                     try    
  110.                     {      
  111.                         file.upload(request);      
  112.                     }    
  113.                     catch (error:Error)    
  114.                     {      
  115.                         Alert.show("上传失败","错误");   
  116.                     }      
  117.                        
  118.                 }      
  119.             }    
  120.                
  121.             private function upload(): void{    
  122.                 var typefiter:FileFilter=new FileFilter("Excel","*.xls");   
  123.                 file.browse([typefiter]);      
  124.             }   
  125.                
  126.             /**CloseEvent事件监听处理函数,关闭TitleWindow弹出窗口   
  127.              * @param e,事件参数   
  128.              * @author  54cwf@163.com   
  129.              * @return void   
  130.              * */   
  131.             private function TitleWindowClose(e:CloseEvent):void   
  132.             {   
  133.                 PopUpManager.removePopUp(this);   
  134.             }   
  135.                
  136.             /**Event事件监听处理函数,获取配置文件的文件上传路径   
  137.              * @param e,事件参数   
  138.              * @author  54cwf@163.com   
  139.              * @return void   
  140.              * */   
  141.             private function CompletedHandler(e:Event):void   
  142.             {   
  143.                 var configurationxml:XML=XML((URLLoader(e.target).data));   
  144.                 serveraddress=configurationxml.filesinservername;   
  145.             }   
  146.         ]]>   
  147.     </fx:Script>   
  148.     <mx:Canvas width="100%" height="100%">      
  149.         <mx:VBox width="100%" horizontalAlign="center">      
  150.             <mx:Label id="lblProgress" text="上传"/>      
  151.             <mx:ProgressBar id="uploadbar" labelPlacement="bottom" themeColor="#F20D7A"      
  152.                             minimum="0" visible="true" maximum="100" label="当前进度: 0%"         
  153.                             direction="right" mode="manual" width="200"/>      
  154.             <mx:Button label="上传文件" click="upload()"/>                   
  155.         </mx:VBox>   
  156.     </mx:Canvas>    
  157. </mx:TitleWindow>  

你可能感兴趣的:(java)