flex上傳文件到wcf restful

wcf restful 代碼
 /// <summary>
        /// 上傳文件
        /// </summary>
        /// <param name="stream">post文件流</param>
        /// <param name="file">提交時附帶信息。本例子中當文件名用</param>
        /// <returns></returns>
        [WebInvoke(UriTemplate = "Add/{file}", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        public SampleItem AddFile(Stream stream, string file)
        {
            //獲取web的上下文
            var ctx = WebOperationContext.Current;

            //判斷附帶信息。沒有信息返回錯誤信息
            if (!string.IsNullOrEmpty(file))
            {
                //獲得服務器保存文件的文件夾路徑
                string folder = System.Web.Hosting.HostingEnvironment.MapPath("~/Files");
                //判斷文件夾是否存在,不在時新建
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                //獲得隨機數
                System.Random objRand = new Random();
                //獲得當前日期
                System.DateTime date = DateTime.Now;
                //生成隨機文件名
              string  saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99) * 97 + 100);
                //拼接出隨進文件名
                 string  fileName = file + saveName;
                //拼接路徑和文件名
                 string path = Path.Combine(folder, fileName);
               
                //保存文件
                    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                    {
                        //獲得上傳文件的大小
                        long ByteLength = WebOperationContext.Current.IncomingRequest.ContentLength;
                        //生成數組
                        byte[] fileContent = new byte[ByteLength];
                        //讀取文件流
                        stream.Read(fileContent, 0, fileContent.Length);
                        //文件寫入
                        fs.Write(fileContent, 0, fileContent.Length);
                        //清空文件流換成
                        fs.Flush();
                       // ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
                        //返回信息
                        return new SampleItem() { Id = 11 , StringValue ="true"};
                    }

                 
            }
            else
            {
              //  ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Accepted;
                //返回錯誤信息
                return new SampleItem() { Id = 22, StringValue = "false" };
            }
        
        }



flex 代碼

<?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"
			   height="100" minWidth="150" minHeight="100">
	<fx:Declarations>
		<!-- 將非可視元素(例如服務、值對象)放在此處 -->
	</fx:Declarations>
	
	<fx:Script>
		<![CDATA[
			import flash.globalization.NumberFormatter;
			
			import mx.controls.Alert;
			import mx.core.FlexGlobals;
			//接收用字段
			[Bindable]
			public var file:String;
			//實例化文件上傳類
			var fileref:FileReference = new FileReference();
			//文件選擇按鈕
			protected function bt_sel_clickHandler(event:MouseEvent):void
			{
				//添加選擇事件監聽
				fileref.addEventListener(Event.SELECT,selectok);
				//添加異常事件監聽
				fileref.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
				//添加上傳完成事件監聽
				fileref.addEventListener(Event.COMPLETE,completeHandler);
				//添加上傳進度事件監聽
				fileref.addEventListener(ProgressEvent.PROGRESS,profun);
				//添加上傳完畢獲取返回數據時間監聽
				fileref.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,dataHandle);
				fileref.browse();
				 
				
			}
			
			//文件選擇
			protected function selectok(event:Event):void
			{
				//獲取選擇目標
				var file:FileReference =  FileReference(event.target);
				//顯示文件嗎
				ti_url.text = file.name;
			
				//fileref.load();
			}
			
			//上傳按鈕時間
			protected function uploadfun(event:MouseEvent):void
			{
				//獲取由外傳入的文件嗎
				var str:String = FlexGlobals.topLevelApplication.parameters.file;
				//如果未傳值設置默認名爲file
				if (str==null || str=="")
				{
					str = "file";
				}
				 //拼接上傳url
				var url:URLRequest = new URLRequest('http://localhost:6309/Service1/Add/' + str ); 
//				if (fileref.data) { 
//					
//					fileref.addEventListener(Event.COMPLETE,uploadok); 
//					fileref.addEventListener(ProgressEvent.PROGRESS,profun); 
//					fileref.upload(url); 
//				} else { 
//					Alert.show('請先瀏覽文件並加載數據!','警告');
//				} 
				
				try
				{
					//上傳
				fileref.upload(url);
					//鼠標設置爲繁忙
				 cursorManager.setBusyCursor()	;
				 //禁用頁面空間
				 setBt(false);
				} 
				catch(error:Error) 
				{
					Alert.show(error.message);
				}
				
				
			}
			
			
			//
//			protected function uploadok(event:Event):void
//			{
//				Alert.show('上傳成功','溫馨提示'); 
//				
//			}
			
			//上傳進度事件監聽
			protected function profun(event:ProgressEvent):void
			{
				//獲取上傳進度
				var i:int = int(event.bytesLoaded/event.bytesTotal*100); 
				//設置進度條
				pg_1.setProgress(i,100);
				
			} 
			
			
			
			
			//異常事件監聽
			protected function ioErrorHandler(event:IOErrorEvent):void
			{
				 
				Alert.show(event.text);
				
			}
			
			//完成事件監聽
			protected function completeHandler(event:Event):void
			{
			 //鼠標設置正常
			cursorManager.removeBusyCursor();
			//激活控件
			setBt(true);
				
			}
			//接收返回數據監聽
			protected function dataHandle(event:DataEvent):void
			{
				//獲取返回數據
				 var data:String = event.data;
				 //Alert.show(data);
				 //調用網頁js方法
				 ExternalInterface.call("swfCallBack",data);
			}
			//設置控件狀態
			protected function setBt(flag:Boolean):void
			{
			 bt_sel.enabled = flag;
			 bt_update.enabled = flag;
			 
			}
			
		]]>
	</fx:Script>
	
	
	<fx:Declarations>
		<!-- 將非可視元素(例如服務、值對象)放在此處 -->
	</fx:Declarations>
	
	
	<s:HGroup left="5" right="5" top="10" height="50" horizontalAlign="center" paddingBottom="0"
			  paddingLeft="0" paddingRight="0" paddingTop="0" verticalAlign="middle">
		<s:TextInput id="ti_url" width="80%" height="30"/>
		<s:Button id = "bt_sel"   height="30" content="選擇文件" click="bt_sel_clickHandler(event)" />
		<s:Button  id ="bt_update"  label="上傳" height="30" click="uploadfun(event)"/> 
		
	</s:HGroup>
	<s:HGroup y="63" left="10" right="10" height="20" horizontalAlign="center" verticalAlign="middle">
		<mx:ProgressBar  mode="manual" height="90%" width="90%" id = "pg_1" maximum="100"/>
	</s:HGroup>
</s:Application>


嵌入頁面代碼


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 
    <!-- 
    Smart developers always View Source. 
    
    This application was built using Adobe Flex, an open source framework
    for building rich Internet applications that get delivered via the
    Flash Player or to desktops via Adobe AIR. 
    
    Learn more about Flex at http://flex.org 
    // -->
    <head>
        <title></title>
        <meta name="google" value="notranslate" />         
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript" language="javascript">
            function swfCallBack(a) {
                alert(a);
            }
        </script>
     
    </head>
    <body>

           <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="300" height="100" id="updateHttp">
                <param name="movie" value="updateHttp.swf" />
                <param name="quality" value="high" />
                <param name="bgcolor" value="#ffffff" />
                <param name="allowScriptAccess" value="sameDomain" />
                <param name="FlashVars" value="file=測試"/>  
                <param name="allowFullScreen" value="true" />
                <!--[if !IE]>-->
                <object type="application/x-shockwave-flash" data="updateHttp.swf" width="300" height="100">
                    <param name="quality" value="high" />
                    <param name="bgcolor" value="#ffffff" />
                    <param name="allowScriptAccess" value="sameDomain" />
                    <param name="FlashVars" value="file=測試"/>  
                    <param name="allowFullScreen" value="true" />
                <!--<![endif]-->
                <!--[if gte IE 6]>-->
                    <p> 
                        Either scripts and active content are not permitted to run or Adobe Flash Player version
                        11.1.0 or greater is not installed.
                    </p>
                <!--<![endif]-->
                    <a href="http://www.adobe.com/go/getflashplayer">
                        <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
                    </a>
                <!--[if !IE]>-->
                </object>
                <!--<![endif]-->
            </objec
      
    
   </body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章