[源码下载]
稳扎稳打Silverlight(20) - 2.0通信之WebClIEnt,以字符串的形式上传/下载数据,以流的方式上传/下载数据
作者: webabcd
介绍
Silverlight 2.0 详解WebClIEnt,以字符串的形式上传、下载数据;以流的方式上传、下载数据
WebClIEnt - 将数据发送到指定的 URI,或者从指定的 URI 接收数据的类
DownloadStringAsync(Uri address,Object userToken) - 以字符串的形式下载指定的 URI 的资源
UploadStringAsync(Uri address,string data) - 以字符串的形式上传数据到指定的 URI。所使用的 http 方法默认为 POST
OpenReadAsync(Uri address,Object userToken) - 以流的形式下载指定的 URI 的资源
OpenWriteAsync(Uri address,string method,Object userToken) - 打开流以使用指定的方法向指定的 URI 写入数据
在线DEMO
http://www.cnblogs.com/webabcd/archive/2008/10/09/1307486.html
示例
1、以字符串的形式和流的形式下载数据
WebClIEntDownload.xaml
< UserControl x:Class ="Silverlight20.Communication.WebClIEntDownload"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" >
< StackPanel HorizontalAlignment ="left" OrIEntation ="Horizontal" >
< StackPanel margin ="5" WIDth ="200" >
< TextBox x:name ="lblMsgString" margin ="5" />
< Progressbar x:name ="progressbarString" Height ="20" margin ="5" Minimum ="0" Maximum ="100" />
</ StackPanel >
< StackPanel margin ="5" WIDth ="200" >
< TextBox x:name ="lblMsgStream" margin ="5" />
< Progressbar x:name ="progressbarStream" Height ="20" margin ="5" Minimum ="0" Maximum ="100" />
< Image x:name ="img" margin ="5" />
</ StackPanel >
</ StackPanel >
</ UserControl >
WebClIEntDownload.xaml.cs
using System;
using System.Collections.Generic;
using System.linq;
using System.Net;
using System.windows;
using System.windows.Controls;
using System.windows.documents;
using System.windows.input;
using System.windows.Media;
using System.windows.Media.Animation;
using System.windows.Shapes;
using System.IO;
namespace Silverlight20.Communication
@H_403_455@ {
public partial class WebClIEntDownload : UserControl
{
// 用于演示以字符串的形式下载数据
string _urlString = "http://localhost/files/Demo.zip";
// 用于演示以流的形式下载数据
string _urlStream = "http://localhost/files/logo.png";
public WebClIEntDownload()
{
InitializeComponent();
// 演示字符串式下载
DownloadStringDemo();
// 演示流式下载
DownloadStreamDemo();
}
/**//// <summary>
/// 演示字符串式下载
/// </summary>
voID DownloadStringDemo()
{
Uri uri = new Uri(_urlString, UriKind.absolute);
/**//*
* WebClIEnt - 将数据发送到指定的 URI,或者从指定的 URI 接收数据的类
* DownloadStringCompleted - 下载数据完毕后(包括取消 *** 作及有错误发生时)所触发的事件
* DownloadProgressChanged - 下载数据过程中所触发的事件。正在下载或下载完全部数据后会触发
* DownloadStringAsync(Uri address, Object userToken) - 以字符串的形式下载指定的 URI 的资源
* Uri address - 需要下载的资源地址
* Object userToken - 用户标识
*/
System.Net.WebClIEnt clIEntDownloadString = new System.Net.WebClIEnt();
clIEntDownloadString.DownloadStringCompleted += new DownloadStringCompletedEventHandler(clIEntDownloadString_DownloadStringCompleted);
clIEntDownloadString.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clIEntDownloadString_DownloadProgressChanged);
clIEntDownloadString.DownloadStringAsync(uri, "userToken");
}
voID clIEntDownloadString_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
/**//*
* DownloadProgressChangedEventArgs.Progresspercentage - 下载完成的百分比
* DownloadProgressChangedEventArgs.BytesReceived - 当前收到的字节数
* DownloadProgressChangedEventArgs.TotalBytesToReceive - 总共需要下载的字节数
* DownloadProgressChangedEventArgs.UserState - 用户标识
*/
lblMsgString.Text = string.Format("下载完成的百分比:{0}/r/n当前收到的字节数:{1}/r/n总共需要下载的字节数:{2}/r/n",
e.Progresspercentage.ToString() + "%",
e.BytesReceived.ToString(),
e.TotalBytesToReceive.ToString());
progressbarString.Value = (double)e.Progresspercentage;
}
voID clIEntDownloadString_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
/**//*
* DownloadStringCompletedEventArgs.Error - 该异步 *** 作期间是否发生了错误
* DownloadStringCompletedEventArgs.Cancelled - 该异步 *** 作是否已被取消
* DownloadStringCompletedEventArgs.Result - 下载后的字符串类型的数据
* DownloadStringCompletedEventArgs.UserState - 用户标识
*/
if (e.Error != null)
{
lblMsgString.Text += e.Error.ToString();
return;
}
if (e.Cancelled != true)
{
lblMsgString.Text += string.Format("用户标识:{0}", e.UserState.ToString());
}
}
/**//// <summary>
/// 演示流式下载
/// </summary>
voID DownloadStreamDemo()
{
Uri uri = new Uri(_urlStream, UriKind.absolute);
/**//*
* WebClIEnt - 将数据发送到指定的 URI,或者从指定的 URI 接收数据的类
* IsBusy - 指定的web请求是否正在进行中
* CancelAsync() - 取消指定的异步 *** 作
* OpenReadCompleted - 数据读取完毕后(包括取消 *** 作及有错误发生时)所触发的事件。流的方式
* DownloadProgressChanged - 下载数据过程中所触发的事件。正在下载或下载完全部数据后会触发
* OpenReadAsync(Uri address, Object userToken) - 以流的形式下载指定的 URI 的资源
* Uri address - 需要下载的资源地址
* Object userToken - 用户标识
*/
System.Net.WebClIEnt clIEntDownloadStream = new System.Net.WebClIEnt();
if (clIEntDownloadStream.IsBusy)
clIEntDownloadStream.CancelAsync();
clIEntDownloadStream.OpenReadCompleted += new OpenReadCompletedEventHandler(clIEntDownloadStream_OpenReadCompleted);
clIEntDownloadStream.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clIEntDownloadStream_DownloadProgressChanged);
clIEntDownloadStream.OpenReadAsync(uri);
}
voID clIEntDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
@H_970_1403@
{/**//*
* DownloadProgressChangedEventArgs.Progresspercentage - 下载完成的百分比
* DownloadProgressChangedEventArgs.BytesReceived - 当前收到的字节数
* DownloadProgressChangedEventArgs.TotalBytesToReceive - 总共需要下载的字节数
* DownloadProgressChangedEventArgs.UserState - 用户标识
*/
lblMsgString.Text = string.Format("下载完成的百分比:{0}/r/n当前收到的字节数:{1}/r/n总共需要下载的字节数:{2}/r/n",
e.TotalBytesToReceive.ToString());
progressbarStream.Value = (double)e.Progresspercentage;
}
voID clIEntDownloadStream_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
/**//*
* OpenReadCompletedEventArgs.Error - 该异步 *** 作期间是否发生了错误
* OpenReadCompletedEventArgs.Cancelled - 该异步 *** 作是否已被取消
* OpenReadCompletedEventArgs.Result - 下载后的 Stream 类型的数据
* OpenReadCompletedEventArgs.UserState - 用户标识
*/
if (e.Error != null)
{
lblMsgStream.Text += e.Error.ToString();
return;
}
if (e.Cancelled != true)
{
System.windows.Media.Imaging.BitmAPImage imageSource = new System.windows.Media.Imaging.BitmAPImage();
imageSource.SetSource(e.Result);
img.source = imageSource;
}
}
}
}
2、以字符串的形式和流的形式上传数据
REST.cs(WCF创建的用于演示以字符串的形式和流的形式上传数据的REST服务)
using System;
using System.linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Collections.Generic;
using System.Text;
using System.IO;
/**/ /// <summary>
/// 提供 REST 服务的类
/// 注:Silverlight只支持 GET 和 POST
/// </summary>
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class REST
{
/**//// <summary>
/// 用于演示返回 JsON(对象) 的 REST 服务
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "User/{name}/Json", ResponseFormat = Webmessageformat.Json)]
public User HelloJson(string name)
{
return new User { name = name, DayOfBirth = new DateTime(1980, 2, 14) };
}
/**//// <summary>
/// 用于演示返回 JsON(集合) 的 REST 服务
/// </summary>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "Users/Json", ResponseFormat = Webmessageformat.Json)]
public List<User> HelloJson2()
{
return new List<User>
{
new User(){ name = "webabcd01", 1, 1) },
new User(){ name = "webabcd02", 2) },
new User(){ name = "webabcd03", 3, 3) },
};
}
/**//// <summary>
/// 用于演示返回 XML(对象) 的 REST 服务
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "User/{name}/xml", ResponseFormat = Webmessageformat.Xml)]
public User HelloXml(string name)
{
return new User { name = name, 14) };
}
/**//// <summary>
/// 用于演示返回 XML(集合) 的 REST 服务
/// </summary>
/// <returns></returns>
[OperationContract]
[WebGet(UriTemplate = "Users/xml", ResponseFormat = Webmessageformat.Xml)]
public List<User> HelloXml2()
{
return new List<User>
{
new User(){ name = "webabcd01",
new User(){ name = "webabcd02",
new User(){ name = "webabcd03",
};
}
/**//// <summary>
/// 用于演示以字符串的形式上传数据的 REST 服务
/// </summary>
/// <param name="filename">上传的文件名</param>
/// <param name="stream">POST 过来的数据</param>
/// <returns></returns>
[OperationContract]
[WebInvoke(UriTemplate = "UploadString/?filename={filename}", Method = "POST", ResponseFormat = Webmessageformat.Json)]
public bool UploadString(string filename, Stream stream)
{
// 文件的服务端保存路径
string path = Path.Combine("C://", filename);
try
{
using (StreamReader sr = new StreamReader(stream))
{
// 将 POST 过来的被 Base64 编码过字符串传换成 byte[]
byte[] buffer = Convert.FromBase64String(sr.ReadToEnd());
using (fileStream fs = new fileStream(path, fileMode.Create, fileAccess.Write, fileShare.None))
{
// 将文件写入到服务端
fs.Write(buffer, 0, buffer.Length);
}
}
return true;
}
catch
{
return false;
}
}
/**//// <summary>
/// 用于演示以流的形式上传数据的 REST 服务
/// </summary>
/// <param name="filename">上传的文件名</param>
/// <param name="stream">POST 过来的数据(流的方式)</param>
/// <returns></returns>
[OperationContract]
[WebInvoke(UriTemplate = "UploadStream/?filename={filename}", ResponseFormat = Webmessageformat.Json)]
public bool UploadStream(string filename, Stream stream)
{
// 文件的服务端保存路径
string path = Path.Combine("C://", filename);
try
{
using (fileStream fs = new fileStream(path, fileShare.None))
{
byte[] buffer = new byte[4096];
int count = 0;
// 每 POST 过来 4096 字节的数据,往服务端写一次
while ((count = stream.Read(buffer, buffer.Length)) > 0)
{
fs.Write(buffer, count);
}
}
return true;
}
catch
{
return false;
}
}
}
WebClIEntUpload.xaml
< UserControl x:Class ="Silverlight20.Communication.WebClIEntUpload"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" >
< StackPanel HorizontalAlignment ="left" OrIEntation ="Horizontal" >
< StackPanel margin ="5" WIDth ="200" >
< TextBox x:name ="lblMsgString" margin ="5" />
< Progressbar x:name ="progressbarString" Height ="20" margin ="5" Minimum ="0" Maximum ="100" />
< button x:name ="btnString" Content ="上传文件(字符串的方式)" margin ="5" Click ="btnString_Click" />
</ StackPanel >
< StackPanel margin ="5" WIDth ="200" >
< TextBox x:name ="lblMsgStream" margin ="5" />
< Progressbar x:name ="progressbarStream" Height ="20" margin ="5" Minimum ="0" Maximum ="100" />
< button x:name ="btnStream" Content ="上传文件(流的方式)" margin ="5" Click ="btnStream_Click" />
</ StackPanel >
</ StackPanel >
</ UserControl >
WebClIEntUpload.xaml.cs
using System;
using System.Collections.Generic;
using System.linq;
using System.Net;
using System.windows;
using System.windows.Controls;
using System.windows.documents;
using System.windows.input;
using System.windows.Media;
using System.windows.Media.Animation;
using System.windows.Shapes;
using System.IO;
using System.windows.Resources;
using System.ComponentModel;
using System.windows.browser;
namespace Silverlight20.Communication
{
public partial class WebClIEntUpload : UserControl
{
// 用于演示以字符串的形式上传数据
string _urlString = "http://localhost:3036/REST.svc/UploadString/?filename=";
// 用于演示以流的形式上传数据
string _urlStream = "http://localhost:3036/REST.svc/UploadStream/?filename=";
public WebClIEntUpload()
@H_15_4199@
{InitializeComponent();
}
/**//// <summary>
/// 演示字符串式上传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private voID btnString_Click(object sender, RoutedEventArgs e)
{
string data = "";
/**//*
* OpenfileDialog - 文件对话框
* ShowDialog() - 显示文件对话框。在文件对话框中单击“确定”则返回true,反之则返回false
* file - 所选文件的 fileInfo 对象
*/
OpenfileDialog dialog = new OpenfileDialog();
if (dialog.ShowDialog() == true)
{
using (fileStream fs = dialog.file.OpenRead())
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, buffer.Length);
// 将指定的 byte[] 转换为字符串(使用Base64编码)
data = Convert.ToBase64String(buffer);
}
/**//*
* WebClIEnt - 将数据发送到指定的 URI,或者从指定的 URI 接收数据的类
* UploadStringCompleted - 上传数据完毕后(包括取消 *** 作及有错误发生时)所触发的事件
* UploadProgressChanged - 上传数据过程中所触发的事件。正在上传或上传完全部数据后会触发
* headers - 与请求相关的的标头的 key/value 对集合
* UploadStringAsync(Uri address, string data) - 以字符串的形式上传数据到指定的 URI。所使用的 http 方法默认为 POST
* Uri address - 接收上传数据的 URI
* string data - 需要上传的数据
*/
System.Net.WebClIEnt clIEntUploadString = new System.Net.WebClIEnt();
clIEntUploadString.UploadStringCompleted += new UploadStringCompletedEventHandler(clIEntUploadString_UploadStringCompleted);
clIEntUploadString.UploadProgressChanged += new UploadProgressChangedEventHandler(clIEntUploadString_UploadProgressChanged);
Uri uri = new Uri(_urlString + dialog.file.name, UriKind.absolute);
clIEntUploadString.headers["Content-Type"] = "application/x-www-form-urlencoded";
clIEntUploadString.UploadStringAsync(uri, data);
}
}
voID clIEntUploadString_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
/**//*
* UploadProgressChangedEventArgs.Progresspercentage - 上传完成的百分比
* UploadProgressChangedEventArgs.BytesSent - 当前发送的字节数
* UploadProgressChangedEventArgs.TotalBytesToSend - 总共需要发送的字节数
* UploadProgressChangedEventArgs.BytesReceived - 当前接收的字节数
* UploadProgressChangedEventArgs.TotalBytesToReceive - 总共需要接收的字节数
* UploadProgressChangedEventArgs.UserState - 用户标识
*/
lblMsgString.Text = string.Format("上传完成的百分比:{0}/r/n当前发送的字节数:{1}/r/n总共需要发送的字节数:{2}/r/n当前接收的字节数:{3}/r/n总共需要接收的字节数:{4}/r/n",
e.Progresspercentage.ToString(),
e.BytesSent.ToString(),
e.TotalBytesToSend.ToString(),
e.TotalBytesToReceive.ToString());
progressbarString.Value = (double)e.Progresspercentage;
}
voID clIEntUploadString_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
/**//*
* UploadStringCompletedEventArgs.Error - 该异步 *** 作期间是否发生了错误
* UploadStringCompletedEventArgs.Cancelled - 该异步 *** 作是否已被取消
* UploadStringCompletedEventArgs.Result - 服务端返回的数据(字符串类型)
* UploadStringCompletedEventArgs.UserState - 用户标识
*/
if (e.Error != null)
{
lblMsgString.Text += e.Error.ToString();
return;
}
if (e.Cancelled != true)
{
var JsonObject = System.Json.JsonObject.Parse(e.Result);
lblMsgString.Text += string.Format("是否上传成功:{0}",
(bool)JsonObject);
}
}
/**//// <summary>
/// 演示流式上传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private voID btnStream_Click(object sender, RoutedEventArgs e)
{
fileStream fs = null;
OpenfileDialog dialog = new OpenfileDialog();
if (dialog.ShowDialog() == true)
{
fs = dialog.file.OpenRead();
/**//*
* WebClIEnt - 将数据发送到指定的 URI,或者从指定的 URI 接收数据的类
* OpenWriteCompleted - 在打开用于上传的流完成时(包括取消 *** 作及有错误发生时)所触发的事件
* WriteStreamClosed - 在写入数据流的异步 *** 作完成时(包括取消 *** 作及有错误发生时)所触发的事件
* UploadProgressChanged - 上传数据过程中所触发的事件。如果调用 OpenWriteAsync() 则不会触发此事件
* headers - 与请求相关的的标头的 key/value 对集合
* OpenWriteAsync(Uri address, string method, Object userToken) - 打开流以使用指定的方法向指定的 URI 写入数据
* Uri address - 接收上传数据的 URI
* string method - 所使用的 http 方法(POST 或 GET)
* Object userToken - 需要上传的数据流
*/
System.Net.WebClIEnt clIEntUploadStream = new System.Net.WebClIEnt();
clIEntUploadStream.OpenWriteCompleted += new OpenWriteCompletedEventHandler(clIEntUploadStream_OpenWriteCompleted);
clIEntUploadStream.UploadProgressChanged += new UploadProgressChangedEventHandler(clIEntUploadStream_UploadProgressChanged);
clIEntUploadStream.WriteStreamClosed += new WriteStreamClosedEventHandler(clIEntUploadStream_WriteStreamClosed);
Uri uri = new Uri(_urlStream + dialog.file.name, UriKind.absolute);
clIEntUploadStream.headers["Content-Type"] = "multipart/form-data";
clIEntUploadStream.OpenWriteAsync(uri, "POST", fs);
}
}
voID clIEntUploadStream_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
// 因为是调用 OpenWriteAsync(),所以不会触发 UploadProgressChanged 事件
lblMsgString.Text = string.Format("上传完成的百分比:{0}/r/n当前发送的字节数:{1}/r/n总共需要发送的字节数:{2}/r/n当前接收的字节数:{3}/r/n总共需要接收的字节数:{4}/r/n",
e.TotalBytesToReceive.ToString());
progressbarStream.Value = (double)e.Progresspercentage;
}
voID clIEntUploadStream_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
System.Net.WebClIEnt clIEnt = sender as System.Net.WebClIEnt;
if (e.Error != null)
{
lblMsgStream.Text += e.Error.ToString();
return;
}
if (e.Cancelled != true)
{
// e.UserState - 需要上传的流(客户端流)
Stream clIEntStream = e.UserState as Stream;
// e.Result - 目标地址的流(服务端流)
Stream serverStream = e.Result;
byte[] buffer = new byte[4096];
int count = 0;
// clIEntStream.Read - 将需要上传的流读取到指定的字节数组中
while ((count = clIEntStream.Read(buffer, buffer.Length)) > 0)
{
// serverStream.Write - 将指定的字节数组写入到目标地址的流
serverStream.Write(buffer, count);
}
serverStream.Close();
clIEntStream.Close();
}
}
voID clIEntUploadStream_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
{
if (e.Error != null)
{
lblMsgStream.Text += e.Error.ToString();
return;
}
else
{
lblMsgStream.Text += "上传完成";
}
}
}
}
/**/ /*
* 其他:
* 1、WebClIEnt 对象一次只能启动一个请求。如果在一个请求完成(包括出错和取消)前,即IsBusy为true时,进行第二个请求,则第二个请求将会抛出 NotSupportedException 类型的异常
* 2、如果 WebClIEnt 对象的 BaseAddress 属性不为空,则 BaseAddress 与 URI(相对地址) 组合在一起构成绝对 URI
* 3、WebClIEnt 类的 AllowReadStreamBuffering 属性:是否对从 Internet 资源接收的数据做缓冲处理。默认值为true,将数据缓存在客户端内存中,以便随时被应用程序读取
*/
OK
[源码下载] 总结
以上是内存溢出为你收集整理的稳扎稳打Silverlight(20) - 2.0通信之WebClient, 以字符串的形式上传/下载数据, 以流的方式上传/下载数据全部内容,希望文章能够帮你解决稳扎稳打Silverlight(20) - 2.0通信之WebClient, 以字符串的形式上传/下载数据, 以流的方式上传/下载数据所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)