flex上传文件到wcf restful

本文介绍了一个使用 WCF RESTful 服务实现的文件上传功能,包括 C# 后端代码示例及 Flex 客户端实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>


电动汽车数据集:2025年3K+记录 真实电动汽车数据:特斯拉、宝马、日产车型,含2025年电池规格和销售数据 关于数据集 电动汽车数据集 这个合成数据集包含许多品牌和年份的电动汽车和插电式车型的记录,捕捉技术规格、性能、定价、制造来源、销售和安全相关属性。每一行代表由vehicle_ID标识的唯一车辆列表。 关键特性 覆盖范围:全球制造商和车型组合,包括纯电动汽车和插电式混合动力汽车。 范围:电池化学成分、容量、续航里程、充电标准和速度、价格、产地、自主水平、排放、安全等级、销售和保修。 时间跨度:模型跨度多年(包括传统和即将推出的)。 数据质量说明: 某些行可能缺少某些字段(空白)。 几个分类字段包含不同的、特定于供应商的值(例如,Charging_Type、Battery_Type)。 各列中的单位混合在一起;注意kWh、km、hr、USD、g/km和额定值。 列 列类型描述示例 Vehicle_ID整数每个车辆记录的唯一标识符。1 制造商分类汽车品牌或OEM。特斯拉 型号类别特定型号名称/变体。型号Y 与记录关联的年份整数模型。2024 电池_类型分类使用的电池化学/技术。磷酸铁锂 Battery_Capacity_kWh浮充电池标称容量,单位为千瓦时。75.0 Range_km整数表示充满电后的行驶里程(公里)。505 充电类型主要充电接口或功能。CCS、NACS、CHAdeMO、DCFC、V2G、V2H、V2L Charge_Time_hr浮动充电的大致时间(小时),上下文因充电方法而异。7.5 价格_USD浮动参考车辆价格(美元).85000.00 颜色类别主要外观颜色或饰面。午夜黑 制造国_制造类别车辆制造/组装的国家。美国 Autonomous_Level浮点自动化能力级别(例如0-5),可能包括子级别的小
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值