`
maloveqiao
  • 浏览: 99632 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

Flex+java+spring 上传和下载文件AIR

    博客分类:
  • flex
 
阅读更多
什么都别说附上代码

UploadFile.java



package com.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.springframework.web.context.support.HttpRequestHandlerServlet;

import sun.misc.Request;



public class UploadFile {
    public void uploadFile(byte[] content, String fileName) throws Exception {
   String filePath=getClass().getClassLoader().getResource("/").getFile();
   filePath=filePath.substring(0, (filePath.lastIndexOf("WEB-INF/classes/")));
      File file = new File(filePath+"file\\");
      if(!file.exists()) file.mkdirs();  //如果目录不存在就新建
      File filePro=new File(filePath+"file\\"+ fileName);
            FileOutputStream stream = new FileOutputStream(filePro);
            if (content != null){
                stream.write(content);
            stream.close();
         }
    
     }
    
}



flex应用组件

分开----------------------------------------------------------------------------------------------------------------------------------------------------------------

FileUploader.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
title="上传文件"
width="609" height="400"
dropShadowVisible="true"
creationComplete="init();"
close="titlewindow1_closeHandler(event)"
backgroundColor="#C6C6C6"
xmlns:timerLoader="com.thams.efile.timerLoader.*">
<s:layout>
  <s:VerticalLayout horizontalAlign="center" paddingTop="10"/>
</s:layout>
<fx:Script>
  <![CDATA[
   import com.thams.efile.vo.FileRefrenceVo;
   import com.thams.utils.ArrayCollectionUtils;
   import com.thams.utils.MenuImageClass;
  
   import flash.utils.getTimer;
  
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.controls.ProgressBar;
   import mx.events.CloseEvent;
   import mx.managers.PopUpManager;
  
   private var fileList:FileReferenceList = new FileReferenceList();  //多选文件的list
   [Bindable]
   private var selectedFiles: ArrayCollection = new ArrayCollection();    //多选的文件分离成文件数组
  
   private var fileRef:FileReference;
  
   public var ip:String;
   public var port:String;
   public var user:String;
   public var pass:String;
  
   /**
    * 初始化
    */
   public function init():void{
    fileList.addEventListener(Event.SELECT,fileSelectHandler);
   }
   /**
    *监听文件选择的处理函数
    */
   public var URL:String;
   private function fileSelectHandler(event: Event): void
   {
    var filesNames:String = "";
    if(fileList.fileList.length>10){
     Alert.show("一次最多只能上传10个文件");
    }else{
     for(var i:int=0;i<fileList.fileList.length;i++){
      var f:FileReference = FileReference(fileList.fileList[i]);  
      if(f.size/(1024*1024)>100){
       //Alert.show(f.name+" 文件不能超过100M!已经移除!");
       filesNames += f.name+" \n";
       continue;
      }
      var file:FileRefrenceVo= new FileRefrenceVo();
      file.fileName = f.name;
      file.fileSize = f.size/1024;
      file.fileType = f.type;
      file.fileRefrence = f;
      var b:Boolean = false;
      for each(var o:FileRefrenceVo in selectedFiles){
       if(o.fileName == file.fileName){
        b = true;
       }
      }
      if(!b){
       selectedFiles.addItem(file);
       browseFile.enabled = false;
       upFile.enabled = true;
       //       saveFile.enabled = false;
      }
     }
     if(filesNames){
      Alert.show(filesNames,"以下文件单个超过100M,已经移除!");
     }
     //     if( fileListSize/(1024*1024)>100 ){
     //      selectedFiles.removeAll();
     //      fileListSize = 0;
     //      Alert.show("文件总大小应小于100M");
     //     }
    }
   }
   /**
    * 点击"浏览"按钮-->选择文件
    */
   private function selectFile():void
   {
    //浏览文件,因为是FileReferenceList所以可以多选. 并用FileFilter过滤文件类型.
    fileList.browse([new FileFilter("所有文件 (*.*)","*.*")]);
   }
  
   /**
    * 上传一个文件,监听文件上传完成事件,递归调用.
    */
   private function doSingleUploadFile():void{

    upFile.enabled = false;
    if(selectedFiles.length>10){
     var b:Boolean = true;
     while(b){
      if(fileList&&fileList.fileList.length>0){
       var fi:FileReference = fileList.fileList.shift();
       for each(var selfi:FileRefrenceVo in selectedFiles){
        if(fi.name == selfi.fileName){
         ArrayCollectionUtils.removeObjFromArrayCollection(selectedFiles,selfi);
        }
       }
      }else{
       b = false;
      }
     }
     Alert.show("一次最多只能上传10个文件","提示");
     browseFile.enabled = true;
    }else{
     if (fileList.fileList&&fileList.fileList.length > 0){
      var f: FileReference = fileList.fileList.shift() as FileReference;
      f.addEventListener(Event.COMPLETE, doSingleUploadFileComplete);
      f.load();
     }else{
      //      saveFile.enabled = true;
      browseFile.enabled = true;
     }
    }
   }
   //   else if( fileListSize/(1024*1024)>100 ){
   //    selectedFiles.removeAll();
   //    fileListSize = 0;
   //    Alert.show("文件总大小应小于100M");
   //   }

   /**
    * 一个文件上传完成事件的处理函数,递归执行上传下一个文件.
    */
   private function doSingleUploadFileComplete(event: Event):void{
    var file: FileReference = event.target as FileReference;
    var filename:String="";
    file.removeEventListener(Event.COMPLETE, doSingleUploadFileComplete);
    var date:Date = new Date();
    filename=date.getFullYear()+date.getMonth()+date.getDate()+date.getMinutes()+date.getSeconds()+((Math.random()*10).toString()).substring(0,1)+((Math.random()*10).toString()).substring(0,1)+((Math.random()*10).toString()).substring(0,1)+file.type;
    upload.uploadFile(file.data,filename);//开始上传
    doSingleUploadFile();
   }
   public function removeFile(f: FileReference): void
   {
    var index: int = selectedFiles.getItemIndex(f);
    if (index != -1)
     selectedFiles.removeItemAt(index);
   }

   protected function PopRemoveUpload(event:CloseEvent):void
   {
   }
      protected function titlewindow1_closeHandler(event:CloseEvent):void
   {
    PopUpManager.removePopUp(this);
   }
  
  ]]>
</fx:Script>
<fx:Declarations>
  <s:RemoteObject id="upload" destination="uploadFile" endpoint="http://192.168.1.103:8080/Lx/messagebroker/amf"/>
</fx:Declarations>
<mx:DataGrid id="dg" width="587" height="291"
     dataProvider="{selectedFiles}">
  <mx:columns>
   <mx:DataGridColumn headerText="文件名" dataField="fileName" width="150" sortable="false"/>
   <mx:DataGridColumn headerText="大小(kb)" dataField="fileSize" width="100" sortable="false"/>
   <mx:DataGridColumn headerText="类型" dataField="fileType" width="70" sortable="false"/>
   <mx:DataGridColumn headerText="上传状态" dataField=""    width="230" sortable="false">
    <mx:itemRenderer>
     <fx:Component>
      <mx:HBox width="130" paddingLeft="2" horizontalGap="2">
       <fx:Script>
        <![CDATA[
         override public function set data(value:Object):void{
          super.data = value;
          data.fileRefrence.addEventListener(ProgressEvent.PROGRESS,progressHandler);
          data.fileRefrence.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,fini);
         }
        
         private function progressHandler(event:ProgressEvent):void{
         
          var procent:uint=event.bytesLoaded/event.bytesTotal*100;
         
         }  
        
         public function fini(event: DataEvent):void{
          progress.visible=true;
          progress.label="完成";
          data.fileRefrence.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,fini);
         }
        ]]>
       </fx:Script>
       <mx:ProgressBar id="progress" width="80%"  
           minimum="0" maximum="100" source="{data.fileRefrence}"
           labelPlacement="center" enabled="true" >
       </mx:ProgressBar>
      </mx:HBox>
     </fx:Component>
    </mx:itemRenderer>
   </mx:DataGridColumn>
  </mx:columns>
</mx:DataGrid>
<s:controlBarContent>
  <s:HGroup horizontalAlign="right" clipAndEnableScrolling="true" paddingBottom="0" paddingTop="0" paddingLeft="10" paddingRight="10" width="100%">
   <s:Button id="browseFile"  label="选择本地文件" toolTip="选择本地文件"   click="selectFile()"/>
   <s:Button id="upFile" label="上传" toolTip="上传"   click="doSingleUploadFile();" enabled="false"/>
   <s:Button id="out" label="退出" toolTip="退出"  width="59"  />
  </s:HGroup>
</s:controlBarContent>
</s:TitleWindow>

分开----------------------------------------------------------------------------------------------------------------------------------------------------------------

FileRefrenceVo.as

package com.thams.efile.vo
{

import flash.net.FileReference;

[Bindable]
public class FileRefrenceVo
{
  public var fileName:String;
  public var fileSize:int;
  public var fileType:String;
  public var fileRefrence:FileReference;
}
}

分开----------------------------------------------------------------------------------------------------------------------------------------------------------------

MenuImageClass.as


package com.thams.utils
{
public class MenuImageClass
{
  [bindable]
  public static  var tuichu:Class;
  [bindable]
  public static var shangyi:Class;
  [bindable]
  public static  var baocun:Class;
  [bindable]
  public static var file:Class;
  public function MenuImageClass()
  {
 
 
 
  }
 
}
}

分开----------------------------------------------------------------------------------------------------------------------------------------------------------------

ArrayCollectionUtils.as

package com.thams.utils
{
import mx.collections.ArrayCollection;

public class ArrayCollectionUtils
{
  public function ArrayCollectionUtils()
  {
  }
 
  public static function removeObjFromArrayCollection(coll:ArrayCollection,obj:Object):ArrayCollection{
   var len:uint = coll.length;
  
   for(var i:Number = len-1; i > -1; i--)
   {
    if(coll.getItemAt(i) == obj)
    {
     coll.removeItemAt(i);
    }
   }
  
   return coll;
  }
}
}

分开----------------------------------------------------------------------------------------------------------------------------------------------------------------

downloadFile.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/mx"
        creationComplete="init();"
        xmlns:fileDow="com.thams.*">
<fx:Declarations>
  <!-- 将非可视元素(例如服务、值对象)放在此处 -->
</fx:Declarations>

-------------------------------------------------------------------------------------文件下载--
<fx:Script>
  <![CDATA[
   import com.thams.downloadFile;
   import com.thams.efile.uploader.FileUploader;
  
   import mx.managers.PopUpManager;
  
  
   public function init():void{
    var win:FileUploader = new FileUploader();
    PopUpManager.addPopUp(win, this, true);
    PopUpManager.centerPopUp(win);
   }
  
  ]]>
</fx:Script>

<fx:Script>
  <![CDATA[
   import flash.display.Sprite;
   import flash.events.*;
   import flash.net.FileReference;
   import flash.net.URLRequest;
   import flash.net.FileFilter;
    private var downloadURL:URLRequest;
    private var file:FileReference;
   
    public function FileReference_download(downloadurl:String,fileNames:Stirng):void{
     downloadURL = new URLRequest();
     downloadURL.url = downloadurl;
     file = new FileReference();
     configureListeners(file);
     file.download(downloadURL, fileNames);
    }
   
    private function configureListeners(dispatcher:IEventDispatcher):void {
     dispatcher.addEventListener(Event.CANCEL, cancelHandler);
     dispatcher.addEventListener(Event.COMPLETE, completeHandler);
     dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
     dispatcher.addEventListener(Event.OPEN, openHandler);
     dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
     dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
     dispatcher.addEventListener(Event.SELECT, selectHandler);
    }
   
    private function cancelHandler(event:Event):void {
     trace("cancelHandler: " + event);
    }
   
    private function completeHandler(event:Event):void {
     trace("completeHandler: " + event);
    }
   
    private function ioErrorHandler(event:IOErrorEvent):void {
     trace("ioErrorHandler: " + event);
    }
   
    private function openHandler(event:Event):void {
     trace("openHandler: " + event);
    }
   
    private function progressHandler(event:ProgressEvent):void {
     var file:FileReference = FileReference(event.target);
     trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
    }
   
    private function securityErrorHandler(event:SecurityErrorEvent):void {
     trace("securityErrorHandler: " + event);
    }
   
    private function selectHandler(event:Event):void {
     var file:FileReference = FileReference(event.target);
     trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url);
    }
  
  

  
  ]]>
</fx:Script>

<s:Button x="300" y="50" label="远程文件下载"
     click="FileReference_download('http://192.168.1.103:8080/项目名/保存的文件夹/要下载的文件',你的要下载的文件名称);"/>

</s:WindowedApplication>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics