flex使用filereference+httphandler实现文件上传/下载

来源:互联网 发布:华为研发 知乎 编辑:程序博客网 时间:2024/05/18 00:39

在flex 的应用开发 中,同asp .net,jsp,php 等应用一样,都会有上传/下载文件 的 应用需求,flex的sdk也为我们提供了专门的类filerefudderence实现文件上传/下载 。flex只是作为一个客户端,要实现上传或下载必须得为其提供一个服务端来接受上传或下载的请求,本文以asp.net中的httphandler作为 文件上传的服务端来完成上传功能。

     ok,我们从flex客户端开始,看看客户端是通过什么方式想服务端发起请求。flex客户端要完成文件上传下载都是通过filerefudderence来实现,首先得定义一个该类型对象实例:

  1. private var statetext:string = "请选择一个文件上传";
  2. //通过调用file对象的方法来完成上传和下载功能
  3. private var file:filereference = new filereference();
复制代码

上传文件通常涉及到的有选择文件、上传文件以及上传完成这些最基本的处理过程。ok,下面我们就以这三个过程为例来看看flex是怎么来完成文件的上传功能。首先为这三个功能点分别添加监听事件处理函数 ,在程序

加载时调用:

  1. internal function initapp():void
  2. {
  3.     file.addeventlistener(event.select,onselected);
  4.     file.addeventlistener(event.complete,oncompleted);
  5.     file.addeventlistener(progressevent.progress,onprogress);
  6. }
复制代码

另外我们也可以不用上面这中定义一个函数在程序加载时调用进行初始化操作,应用程序(mxml )的初始化操作又creationcomplete方法完成,另外还有一个比它先执行的方法createchildren(),我们可以直接在mxml下重写该方法来实现应用程序的初始化,如下:

  1. /**
  2. * createchildren 比 creationcomplete 事件更早发生
  3. * */
  4. protected override function createchildren():void
  5. {
  6.     file.addeventlistener(event.select,onselected);
  7.     file.addeventlistener(event.complete,oncompleted);
  8.     file.addeventlistener(progressevent.progress,onprogress);
  9. }
复制代码

这三个事件处理函数的详细定义如下(其中的statetext为string的变量,用于显示文件上传状态提示):

  1. internal function onselected(evt:event):void
  2. {
  3.      statetext = "选择了文件" + file.name;
  4. }
  5. internal function oncompleted(evt:event):void
  6. {
  7.      statetext = "上传完毕!";
  8. }
  9. internal function onprogress(evt:progressevent):void
  10. {
  11.      statetext = "已上传 " + math.round(100 * evt.bytesloaded / evt.bytestotal) + "%";
  12. }
复制代码

到这里客户端就只差一步了,那就是完成发起上传请求的方法,实际上就是通过urlrequest对象创建一个与服务端的连接,然后直接调用fielreference类的upload()方法就可完成该功能,详细如下代码定义:

  1. /**
  2.   * 调用filereference的实例方法upload()实现文件上传
  3.   * */
  4. internal function onupload():void
  5. {
  6.      if(file.size > 0)
  7.      {
  8.          statetext = "正在上传文件:" + file.name;
  9.      }
  10.     var request:urlrequest = new urlrequest();
  11.     request.url="http://localhost/web/uploadhandler.ashx";
  12.     file.upload(request);
  13. }
复制代码

写好了upload方法,现在就是调用他了,通过按扭的click事件直接调用就可以,另外调用file.browse()方法则实现选择文件的功能,如下mxml代码描述:

  1. <mx:textinput x="10" y="57" id="txtfile" text="{statetext}" width="229"/>
  2. <mx:button x="247" y="57" label="选择" fontweight="normal" click="{file.browse()}"/>
  3. <mx:button x="29" y="111" label="上传文件" width="111" fontweight="normal" click="onupload()"/>
复制代码

如上便完成了上传文件的flex客户端开发,通过file.upload()方法,将把选择的文件通过二进制的形式发送到指定的服务端,并自动传递一个叫 “filename”的参数,服务端通过filename便可以接收到客户端请求上传的文件。最后我们来看看服务端的 uploadhandler.ashx的详细定义:

  1. public class uploadhandler : ihttphandler
  2. {
  3.      //文件上传目录
  4.      private string uploadfolder = "upload";
  5.      public void processrequest(httpcontext context)
  6.      {
  7.          context.response.contenttype = "text/plain";
  8.         httpfilecollection files = context.request.files;
  9.         if (files.count > 0)
  10.         {
  11.             string path = context.server.mappath(uploadfolder);
  12.             httppostedfile file = files[0];
  13.             if (file != null && file.contentlength > 0)
  14.             {
  15.                 string savepath = path + "/" + context.request.form["filename"];
  16.                 file.saveas(savepath);
  17.             }
  18.         }
  19.         else
  20.         {
  21.             context.response.write("参数错误");
  22.             context.response.end();
  23.         }
  24.     }
  25.     public bool isreusable
  26.     {
  27.         get
  28.         {
  29.             return false;
  30.         }
  31.     }
  32. }
复制代码

如上一系列的步骤便可完成上传文件的功能,下面便是上传文件示例程序运行 截图:   



   实现了文件上传下面来看看怎么实现文件下载, 以上面上传示例中上传的mp3为例,下面我们来看看怎么从服务器(http://localhost/web/upload/做你的爱人.mp3)上完成文件(做你的爱人.mp3)的下载。

     要实现文件下载对服务器端只要保证被下载文件存在就ok,同上传文件一样需要实例化一个fielreference对象的实例,并为其添加相应的事件处理函数:

private var filedown:filereference = new filereference();


/**
  * createchildren 比 creationcomplete 事件更早发生
  * */
protected override function createchildren():void
{
     super.createchildren();
     file.addeventlistener(event.select,onselected);
     file.addeventlistener(event.complete,oncompleted);
     file.addeventlistener(progressevent.progress,onprogress);
    //实现文件下载
    filedown.addeventlistener(event.complete,ondowncompleted);
    filedown.addeventlistener(progressevent.progress,ondownprogress);
}


     如上为实现下载文件的实例filedown注册了成功下载文件后事件处理函数和下载过程处理函数,下面是两个方法的详细定义:

  1. internal function ondowncompleted(evt:event):void
  2. {
  3.      var fileref:filereference = evt.currenttarget as filereference;
  4.      resultlabel.text = "文件名:" + fileref.name + "下载完毕!";
  5. }
  6. internal function ondownprogress(evt:progressevent):void
  7. {
  8.      downstate.text = "已下载: " + math.round(100 * evt.bytesloaded / evt.bytestotal) + "%";
  9. }
复制代码

完成了对象事件的开发,最后便上惩罚下载请求了,直接调用filereference类所提供的download()方法既可:

  1. /**
  2. * 调用filereference类的实例方法download()实现文件下载
  3. * */
  4. internal function ondownload():void
  5. {
  6.     var request:urlrequest = new urlrequest();
  7.     request.url="http://localhost:1146/upload/做你的爱人.mp3";
  8.     filedown.download(request);
  9. }
复制代码

程序执行到download()方法的时候会自动弹出选择保存文件对话框,根据实际情况选择好保存路径就ok。下面是实现上传和下载的完整代码:

实现上传和下载的完整代码

  1.   <?xml version="1.0" encoding="utf-8"?>
  2.   <mx:application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  3.       <mx:panel x="49" y="66" width="551" height="164" layout="absolute"
  4.           title="使用filereference上传/下载文件" fontsize="12">
  5.           <mx:hdividedbox x="10" y="10" width="511" height="102">
  6.               <mx:canvas  id="left" backgroundcolor="#d7f4ff" height="100%" width="209">
  7.               <mx:textinput x="4" y="20" id="txtfile" text="{statetext}" width="135"/>
  8.               <mx:button x="147" y="20" label="选择" fontweight="normal" click="{file.browse()}"/>
  9.               <mx:button x="31" y="68" label="上传文件" width="111" fontweight="normal" click="onupload()"/>
  10.              </mx:canvas>
  11.              <mx:canvas id="right" backgroundcolor="#d7f4ff" height="100%" width="282">
  12.                  <mx:label x="6" y="9" text="http://localhost/web/upload/做你的爱人.mp3"/>
  13.                  <mx:button x="10" y="37" label="下载文件" fontweight="normal" click="ondownload()"/>
  14.                  <mx:label x="10" y="74" width="272" id="resultlabel"/>
  15.                  <mx:textinput x="122" y="37" id="downstate"/>
  16.              </mx:canvas>
  17.          </mx:hdividedbox>
  18.          
  19.      </mx:panel>
  20.          <mx:script>
  21.          <![cdata[
  22.              [bindable]
  23.              private var statetext:string = "请选择一个文件上传";
  24.             
  25.              private var file:filereference = new filereference();
  26.              private var filedown:filereference = new filereference();
  27.             
  28.              /**
  29.               * createchildren 比 creationcomplete 事件更早发生
  30.               * */
  31.              protected override function createchildren():void
  32.              {
  33.                  super.createchildren();
  34.                  file.addeventlistener(event.select,onselected);
  35.                  file.addeventlistener(event.complete,oncompleted);
  36.                  file.addeventlistener(progressevent.progress,onprogress);
  37.                  
  38.                  filedown.addeventlistener(event.complete,ondowncompleted);
  39.                  filedown.addeventlistener(progressevent.progress,ondownprogress);
  40.              }
  41.             
  42. //            internal function initapp():void
  43. //            {
  44. //                file.addeventlistener(event.select,onselected);
  45. //                file.addeventlistener(event.complete,oncompleted);
  46. //                file.addeventlistener(progressevent.progress,onprogress);
  47. //            }
  48.             
  49.              internal function onselected(evt:event):void
  50.              {
  51.                  statetext = "选择了文件:" + file.name;
  52.              }
  53.             
  54.              internal function oncompleted(evt:event):void
  55.              {
  56.                  statetext = "上传完毕!";
  57.              }
  58.             
  59.             
  60.              internal function ondowncompleted(evt:event):void
  61.              {
  62.                  var fileref:filereference = evt.currenttarget as filereference;
  63.                  resultlabel.text = "文件名:" + fileref.name + "下载完毕!";
  64.              }
  65.             
  66.              internal function onprogress(evt:progressevent):void
  67.              {
  68.                  statetext = "已上传: " + math.round(100 * evt.bytesloaded / evt.bytestotal) + "%";
  69.                  
  70.              }
  71.             
  72.              internal function ondownprogress(evt:progressevent):void
  73.              {
  74.                  downstate.text = "已下载: " + math.round(100 * evt.bytesloaded / evt.bytestotal) + "%";
  75.              }
  76.             
  77.              /**
  78.               * 调用filereference的实例方法upload()实现文件上传
  79.               * */
  80.              internal function onupload():void
  81.              {
  82.                  if(file.size > 0)
  83.                  {
  84.                      statetext = "正在上传文件:" + file.name;
  85.                  }
  86.                  var request:urlrequest = new urlrequest();
  87.                  request.url=http://localhost/web/uploadhandler.ashx;
  88.                  file.upload(request);
  89.              }
  90.             
  91.              /**
  92.               * 调用filereference类的实例方法download()实现文件下载
  93.               * */
  94.              internal function ondownload():void
  95.              {
  96.                  var request:urlrequest = new urlrequest();
  97.                  request.url="http://localhost/web/upload/做你的爱人.mp3";
  98.                  filedown.download(request);
  99.              }
  100.         ]]>
  101.     </mx:script>
  102. </mx:application>
0 0