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

被折叠的 条评论
为什么被折叠?



