单文件上传-flex版本

1.web.config
appSettings配置节
<add key="UploadFileUrl" value="http://file.mydomain.com/" />
<add key="UploadFilePath" value="E:\file.mydomain.com\uploadfile\"/>

2.asp.net文件接收保存处理程序
//UploadHandler.ashx
<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;

public class UploadHandler : IHttpHandler
{
    private string uploadFolder = System.Configuration.ConfigurationManager.AppSettings["UploadFilePath"];

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        HttpFileCollection files = context.Request.Files;
        if (files.Count > 0)
        {
            string orgName = "MyDomain";
            string path = uploadFolder + orgName;
            System.IO.Directory.CreateDirectory(path + "\\");
            HttpPostedFile file = files[0];
            if (file != null && file.ContentLength > 0)
            {
                string guid = System.Guid.NewGuid().ToString();
                string savePath = path + "/" + guid + "_" + context.Request.Form["fileName"];
                file.SaveAs(savePath);

                string url = System.Configuration.ConfigurationManager.AppSettings["UploadFileUrl"] + orgName + "/" + guid + "_" + context.Request.Form["fileName"];
                context.Response.Write(url);
            }
        }
        else
        {
            context.Response.Write("");
            context.Response.End();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

3.flex应用程序,
//本人使用flex builder 4.0
//UploadFile.mxml
//此段程序修改自cnblogs的某一个仁兄的代码,等我找回来了,再把他的文章url贴在这里。google搜过来的。
<?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/halo" minWidth="1024" minHeight="768">

       <mx:Panel x="2" y="2" width="396" height="244" layout="absolute"
           title="FrontSql上传文件" fontSize="12">
           <mx:HDividedBox x="10" y="10" width="377" height="193">
               <mx:Canvas  id="left" backgroundColor="#D7F4FF" height="193" width="358">
               <mx:TextInput x="4" y="51" id="txtFile" text="{stateText}" width="271"/>
               <mx:Button x="279" y="52" label="选择" fontWeight="normal" click="{file.browse()}"/>
               <mx:Button x="117" y="90" label="确定上传" width="69" fontWeight="normal" click="onUpLoad()"/>
               <mx:Label x="5" y="14" text="请选择一个文件上传" width="268"/>
               <mx:Label x="6" y="130" width="269" height="22" id="lblResult"/>
               <mx:TextInput x="6" y="155" width="269" id="lblURL"/>
               <s:Button x="203" y="90" label="关闭" id="bClose" click="onClose()"/>
               <s:Button x="281" y="156" label="查看" id="bView" click="onView()"/>
              </mx:Canvas>
          </mx:HDividedBox>
         
      </mx:Panel>
          <fx:Script>
          <![CDATA[
            import flash.net.navigateToURL;
            import mx.controls.Alert;
             [Bindable]
             private var stateText:String = "";            
             private var file:FileReference = new FileReference();
             private var isSelectedFile:Boolean = false;

             protected override function createChildren():void
             {
                 super.createChildren();
                 file.addEventListener(Event.SELECT,onSelected);
                 file.addEventListener(Event.COMPLETE,onCompleted);
                 file.addEventListener(ProgressEvent.PROGRESS,onProgress);
                 file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadCompleteData);
             }
            
            
             internal function onSelected(evt:Event):void
             {
                 stateText = "选择了文件:" + file.name;
                 isSelectedFile = true;
             }
            
             internal function onCompleted(evt:Event):void
             {
                 lblResult.text = "上传完毕!";
                 lblURL.visible = true;
                 bView.visible = true;
                 ExternalInterface.call("setURL", lblURL.text);
             }
            
             internal function onUploadCompleteData(evt:DataEvent):void
             {
              lblURL.text = evt.data;
              ExternalInterface.call("setURL", lblURL.text);
             }
            
             internal function onProgress(evt:ProgressEvent):void
             {
                 lblResult.text = "已上传: " + Math.round(100 * evt.bytesLoaded / evt.bytesTotal) + "%";
             }

             /**
              * 调用FileReference的实例方法upload()实现文件上传
              * */
             internal function onUpLoad():void
             {
              if(isSelectedFile)
              {
    if(file.size > 0)
    {
        stateText = "正在上传文件:" + file.name;
    }
    var request:URLRequest = new URLRequest();
    request.url="http://www.mydomain.com/UpLoadHandler.ashx";
    file.upload(request); 
               }       
             }
            
             internal function onClose():void
             {
              // call js
              ExternalInterface.call("setURL", lblURL.text);  
              ExternalInterface.call("closeWindowURL",lblURL.text);
             }
            
             internal function onView():void
             {
              if(lblURL.text != ""){
               var http://www.cnblogs.com/xushop/admin/URLRequest = new URLRequest(lblURL.text);
               flash.net.navigateToURL(url,"_blank");
               //ExternalInterface.call("viewURL", lblURL.text);  
              }
              else{
               
               Alert.show("没有文件可看");
              }
             }
         ]]>
     </fx:Script>

</s:Application>


4.修改index.template.html文件
//增加一段js
<script type="text/javascript">
function closeWindow(){
 var u = document.getElementById("urlValue");
 window.returnValue = u.value;
 window.close();
}

function closeWindowURL(url){
 window.returnValue = url;
 window.close();
}

function setURL(url){
 var u = document.getElementById("urlValue");
 u.value = url;
 //alert(url);
 //alert(u.value);
}

function viewURL(url)
{
 window.open(url);
}

window.onunload = closeWindow;

</script>

5.把编译好的flash上传到站点/uploadfile下面


6.使用
<HTML>
<HEAD>
<script language="javascript" >
    function ShowFlexUploadFile(fileUrlTextBox){
 if(fileUrlTextBox != ""){
         var currentFileUrlTextBox = document.all[fileUrlTextBox];
         var result=window.showModalDialog("/uploadfile/UploadFile.html","","dialogWidth:400px;dialogHeight:300px;center=yes;");
         if(result == "") return;
   if(typeof(result)=="undefined") return;
   currentFileUrlTextBox.value = result;
     }
    }
</script>
</HEAD>
<BODY>
<input type='text' ID="txtFileUrl"  style="width:220px"  />&nbsp;<a href="javascript:void(0)"  title="Upload File" onclick="javascript:ShowFlexUploadFile('txtFileUrl');" >Upload</a>
</BODY>
</HTML>

posted @ 2009-09-29 21:30  XuShop  阅读(451)  评论(1编辑  收藏  举报