WebClient思路及功能实现
实现思路:通过新建一个“一般处理程序”WebClientUpLoadStreamHandler.ashx配合完成,
Silverlight打开文件,获取文件流,webclient调用openwrite方法,请求服务器,打开一个可以写进流InputStream。
当该可写进流可用的时候,相应openwrite异步方法的一个回调事件,在该事件中将文件流写进到HTTP的可写进流。服务器端接收到输进流后写进到文件流保存。
服务端使用ASHX一般处理程序来作为接受页。
本程序中添加“一般处理程序”及其用法介绍请单击此处,关于一般处理程序的详细理论介绍请参考http://www.cnblogs.com/JimmyZhang/archive/2007/09/15/894124.html
上传功能实现
一.选择本地图片并指定上传处理上传的一般处理程序
/// <summary>
/// 上传事件通过对话框来选择上传文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog()==true)
{
fileinfo = openFileDialog.File;
if (fileinfo!=null)
{
WebClient webclient = new WebClient();
string uploadFileName = fileinfo.Name.ToString();
Uri upTargetUri = new Uri(String.Format ("http://localhost:"+HtmlPage.Document.DocumentUri.Port+"/WebClientUpLoadStreamHandler.ashx?fileName={0}", uploadFileName), UriKind.Absolute); //指定上传处理程序
webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler (webclient_OpenWriteCompleted);
//webclient.Headers["Content-Type"] = "multipart/from-data";
webclient.OpenWriteAsync(upTargetUri, "POST", fileinfo.OpenRead());
webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed);
}
else
{
MessageBox.Show("请选择想要上传的图片!!!");
}
}
}
void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
//将图片数据流发送到服务器上 e.UserState即为需要上传的客户端的流
Stream clientStream = e.UserState as Stream;
Stream serverStream = e.Result;
byte[] buffer = new byte[4096];
int readcount = 0;
//将需要上传的流读取到指定的字节数组中
while ((readcount = clientStream.Read(buffer,0,buffer.Length))>0)
{
//将指定的字节数组写入到目标地址的流
serverStream.Write(buffer, 0, readcount);
}
serverStream.Close();
clientStream.Close();
}
void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
{
if (e.Error!=null)
{
System.Windows.Browser.HtmlPage.Window.Alert(e.Error.Message);
}
else
{
System.Windows.Browser.HtmlPage.Window.Alert("图片上传成功!!!");
c.GetFileListAsync();//这里是使用了WCF服务返回一下服务端的文件列表,共下载时选择
}
}
二.服务端获得上传流,并保存文件
服务端使用了一般处理程序来配合完成,如何添加一般处理程序请点击此处
public void ProcessRequest(HttpContext context)
{
string fileNamestr = context.Request.QueryString["fileName"];
Stream sr = context.Request.InputStream;//从客户端获得传入到服务端的文件流
try
{
byte[] buffer = new byte[4096];
int bytestRead = 0;
//将当前数据流写入服务器端指定文件夹下
string targetPath = context.Server.MapPath("UploadFiles/"+fileNamestr);
using (FileStream fs = File.Create(targetPath, 4096))
{/
//将当前流读入到字节数组中
while ((bytestRead = sr.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, bytestRead);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("上传成功");
}
catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write("上传失败,错误信息:" + e.Message);
}
finally { sr.Dispose(); }
}
下载功能实现
在客户端直接调用WebClient的自带方法和事件即可完成下载功能
private void buttonDownload_Click(object sender, RoutedEventArgs e)
{
if (listBox1.SelectedItems.Count<0)
{
MessageBox.Show("请选择要下载的下载文件");
}
else if (listBox1.SelectedItems.Count>1)
{
MessageBox.Show("暂不提供批量下载");
}
else
{
string imgUrl = "http://localhost:" + HtmlPage.Document.DocumentUri.Port + "/UploadFiles/" + listBox1.SelectedItem.ToString();
Uri endpoint = new Uri(imgUrl);
WebClient client = new WebClient();
//调用WebClient自身事件
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
//调用自身的Read方法完成下载
client.OpenReadAsync(endpoint);
}
}