大叔家达文西鞋业黑料:Silverlight WebClient 上传实现
来源:百度文库 编辑:中财网 时间:2024/04/28 13:02:16
之前探讨过了 Silverlight通过 WCF实现上传的办法,当初看看另一种Silverlight实现上传的方式 :WebClient类实现上传,同时WEBCLIENT的 OPENWRITE也是官方供给的通常的上传方法,因为他完整就是HTTP实现上传的底本模式,及树立HTTP衔接,翻开一个可写入流,而后将文件流写入到HTTP写入流中实现,而WCF是通过传递字节数组参数的方法,两则之间看似差未几,实际上工作原理很不同。
webclient类中有多少个方法,其中大部门都是请求获取相应流,只有openwrite方法是写入流。所以我们使用该方法实现上传。
工作方式:
Silverlight打开文件,获取文件流,webclient 调用openwrite方法,请求服务器,打开一个可以写入流 InputStream
当该可写入流可用的时候,相应openwrite异步方法的一个回调事件,在该事件中将文件流写入到HTTP的可写入流。服务器端吸收到输入流后写入到文件流保留。
服务器端:(我擦用ASHX作为服务器端接受页,因为咱们不须要返回什么信息,只接收请求,所以没用ASPX页,不外要应用ASPX也可以)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
namespace WebApp4SL
{
/// /// $codebehindclassname$ 的摘要解释 ///
[WebService(Namespace = "")]
[WebServiceBinding(C cdth= WsiProfiles.BasicProfile1_1)]
public class WebClientUpload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Stream s = context.Request.InputStream;
FileStream fs = new FileStream(context.Server.MapPath("UploadFile") + "/" + "asdf.jpg",FileMode.Create);
byte[] bytes = new byte[s.Length];
s.Read(bytes,0,bytes.Length);
fs.Write(bytes,0,bytes.Length);
fs.Flush();
fs.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
客户端处置代码:
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 SilverlightTest
{
public partial class WebClientUpLoad : UserControl
{
public WebClientUpLoad()
{
InitializeComponent();
}
private void openfile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == true)
{
FileStream fs = op.File.OpenRead();
WebClient wc = new WebClient();
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
wc.OpenWriteAsync(new Uri("WebClientUpload.ashx",UriKind.Relative),"POST",fs);
}
}
void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
try
{
Stream fs = (Stream)e.UserState;
Stream inputstream = e.Result;
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
inputstream.Write(bytes, 0, bytes.Length);
inputstream.Close();
fs.Close();
}
catch
{
info.Text = e.Error.InnerException.Message;
}
}
}
}
界面:(切实献丑,界面基础上就个按钮会用到,由于只是为了阐明WEBCLIENT的上传,所以没做什么界面上的开发)
xmlns=""
xmlns:x=""
Width="400" Height="300">
WEBCLIENT 的OPENWRITE还有个UploadProgressChanged事件,该事件指定好对应的处理函数后还可以用来获取上传进度,所以用webclient来实现上传仍是无比便利的,与WCF比拟起来,WCF可以自在的设置参数,但是WCF的字节数组参数长度是有限度的固然能够在WEBCONFIG里进行设置,但是WCF实现上传不是官方提供的解决计划;Webclient 的Openwrite方法是官方提供的文件上传解决方案,工作原理继续传统的HTTP文件上传,同时因为发动读取文件写入流都是在客户端异步进行,所以,及时要实现分块也十分轻易(webclient的其余大局部方法不容许在之前的恳求没实现前进行第2次请求,然而openwrite的文档中没用说明制约,我本人也没试验过,51过后再研讨),但是webclient要求服务器传递参数上不够机动,安排方面也不WCF那么疏松,所以WCF上传跟webclient上传都是可行的,但是详细名目详细剖析,采用最好的最恰当的方式实现。