Flex 上传下载之flex

Upload.mxml

 

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:fx="http://ns.adobe.com/mxml/2009"
     xmlns:s="library://ns.adobe.com/flex/spark"
     xmlns:mx="library://ns.adobe.com/flex/mx">
 <fx:Script>
  <![CDATA[
   import mx.controls.Alert;
   import flash.net.FileReference;
   public var myFileReference:FileReference = new FileReference();
   private function init():void{
    
    process.label = "0 bytes"
    showDetail.text = "无文件上传";
   }
   private function browse():void{

    var typeFilter:FileFilter = new FileFilter("Images(*.jpg,*.png,*.gif)","*.jpg;*.png;*.gif");
    var allTypes:Array = new Array(typeFilter);
    //浏览本地本地文件
    //myFileReference.browse(allTypes);
     myFileReference.browse();
    //为打开选择框定义事件处理
    myFileReference.addEventListener(Event.SELECT, selectHandler);
    //在上传过程中触发的事件处理
    myFileReference.addEventListener(ProgressEvent.PROGRESS, onProcess);
    myFileReference.addEventListener(Event.COMPLETE, onComplete);
   }      
   private function selectHandler(event:Event):void{       
    sName.text = myFileReference.name;
   }
   private function upload():void{
    //Security.allowDomain("*");
    //调用upload.jsp.接受从flash player发送的文件
    var request:URLRequest = new URLRequest("http://localhost:8080/flex/upload.jsp")
    try
    {
     //上传文件
     myFileReference.upload(request);
     showDetail.text = "upload";
    }
    catch (error:Error)
    {
     mx.controls.Alert.show("上传出错");
    }
   }
   private function onProcess(event:ProgressEvent):void{
    var proc:uint = event.bytesLoaded;
    var total:uint = event.bytesTotal;
    process.setProgress(proc,total);
    showDetail.text = "上传中";
    process.label = proc.toString() +" bytes";
   }
   private function onComplete(event:Event):void{
    showDetail.text = "上传结束"; 
    sName.text="";
    this.parentDocument.download.init();
   }
   //取消事件
   private function cancel():void{
    myFileReference.cancel();
   }
  ]]>
 </fx:Script>
 <mx:Button x="330" y="41" label="浏览" click="browse()"/>
 <mx:TextInput  id="sName" x="26" y="39" width="272"/>
 <mx:Button x="26" y="81" label="上传" click="upload()"/>
 <mx:Button x="110.5" y="81" label="取消" click="cancel()"/>
 <mx:ProgressBar  id="process" x="26" y="172" width="360" mode="manual" labelPlacement="right"/>
 <mx:Label x="26" y="125" text="当前状态"/>
 <mx:Text  id="showDetail" x="110" y="125" width="188"/>
</mx:Canvas>

 

 

Download.mxml

 

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas 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()">
 <fx:Declarations>
  <mx:HTTPService id="getList" url="http://localhost:8080/flex/list.jsp" result="resultHandler(event)"
      resultFormat="xml" method="POST">
   <mx:request>
    <someValue>{Math.random()}</someValue>
   </mx:request>
  </mx:HTTPService>
 </fx:Declarations>
 <fx:Script>
  <![CDATA[
   import mx.collections.XMLListCollection;
   import mx.rpc.events.ResultEvent;
   import mx.controls.Alert;
   public var filePath:String;
   public var myFileReference:FileReference = new FileReference();
   public function init():void{
    getList.send();    
    process1.label = "0 bytes";
   }
   private function down():void{
    var u:String = "http://localhost:8080/flex/down.jsp?file="+filePath;
    var request:URLRequest = new URLRequest(u);
    myFileReference.download(request);
    myFileReference.addEventListener(ProgressEvent.PROGRESS, onProcess);
    myFileReference.addEventListener(Event.COMPLETE, onComplete);
   }
   private function onProcess(event:ProgressEvent):void{
    var proc:uint = event.bytesLoaded;
    var total:uint = event.bytesTotal;
    process1.setProgress(proc,total);
    process1.label = proc.toString() +" bytes";
   }
   private function resultHandler(event:ResultEvent):void{
    var x:XML = new XML(event.result);
    fileList.dataProvider = x.item;
    getList.request.someValue = Math.random();
   }
   private function listChange():void{
    var fName:String= fileList.selectedItem.toString();
    fN.text = fName;
    filePath = fName;
   }
   private function onComplete(event:Event):void{
    mx.controls.Alert.show("下载完成");
   }
  ]]>
 </fx:Script>
 <mx:List  id="fileList" x="10" y="34" height="232" width="184" change="listChange()"></mx:List>
 <mx:Label x="10" y="8" text="可下载文件"/>
 <mx:Label x="217" y="34" text=" 从列表中选择要下载的文件"/>
 <mx:Label  id="fN" x="217" y="60" text="文件名"/>
 <mx:LinkButton x="362" y="176" label="下载" click="down()"/>
 <mx:ProgressBar  id="process1" x="202" y="238" mode="manual"/>
</mx:Canvas>

 

Updown.mxml

 

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:local="*">
 
 <mx:TabNavigator id="ud" x="155" y="102" width="445" height="400">
  <local:Upload id="up" label="上传文件">
   
  </local:Upload>
  
  <local:Download  id="download" label="下载文件">
   
  </local:Download>
 </mx:TabNavigator>
 
</s:Application>

 

 

upload.jsp

 

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8" import="java.io.*,java.util.*"%>
<%@page import="com.oreilly.servlet.multipart.*"%>
<%@page import="com.oreilly.servlet.*"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>JSP Page</h1>
        <%
        try {
            //上传文件最大为10M
            MultipartRequest multi =
                    new MultipartRequest(request, "D:/email/", 10*1024*1024,
                    "UTF-8", new DefaultFileRenamePolicy());
            out.println("PARAMS:");
            Enumeration params = multi.getParameterNames();
            while (params.hasMoreElements()) {
                String name = (String)params.nextElement();
                String value = multi.getParameter(name);
                out.println(name + "=" + value);
            }
            out.println();
            out.println("FILES:");
            Enumeration files = multi.getFileNames();
            while (files.hasMoreElements()) {
                String name = (String)files.nextElement();
                String filename = multi.getFilesystemName(name);
                String originalFilename = multi.getOriginalFileName(name);
                String type = multi.getContentType(name);
                File f = multi.getFile(name);
                out.println("name: " + name);
                out.println("filename: " + filename);
                out.println("originalFilename: " + originalFilename);
                out.println("type: " + type);
                if (f != null) {
                    out.println("f.toString(): " + f.toString());
                    out.println("f.getName(): " + f.getName());
                    out.println("f.exists(): " + f.exists());
                    out.println("f.length(): " + f.length());
                }
                out.println();
            }
        } catch (IOException lEx) {
            this.getServletContext().log(lEx, "error reading or saving file");
        }
        %>
    </body>
</html>

 

list.jsp

 

<%@ page contentType="text/html;charset=utf-8"%>
<%@page import="java.io.File"%>
<?xml version='1.0' encoding='utf-8'?>
<list>
        <%
  //定义可下载文件的目录。所有可下载的文件都放在该目录下
  File f =new File("D:/email/");
 File[] l = f.listFiles();
 //循环获取文件下载文件的名称,并加入到XML标签中
 for(int i=0;i<l.length;i++){
  String fName = l[i].getName();
  out.print("<item>");
  out.print(fName);
    out.print("</item>");
 }
      %>
</list>

 

download.jsp

 

<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>JSP Page</h1>
        <%
    String filename = "";
    if (request.getParameter("file") != null) {
        filename =     request.getParameter("file");
    }
    response.setContentType("application/x-msdownload");
    response.setHeader("Content-disposition","attachment; filename="+filename);
   
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(new FileInputStream("d:/email/"+filename));
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff,0,bytesRead);
        }
    } catch(final IOException e) {
        System.out.println ( "Exception." + e );
    } finally {
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
   %>
    </body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值