silverlight webclient实现上传、下载、删除、读取文件

时间:2023-03-09 03:58:30
silverlight webclient实现上传、下载、删除、读取文件

1.上传

  private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog()
{ //弹出打开文件对话框要求用户自己选择在本地端打开的图片文件
Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*",
Multiselect = false //不允许多选
}; if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
{
//fileinfo = openFileDialog.Files; //取得所选择的文件,其中Name为文件名字段,作为绑定字段显示在前端
FileInfo fileinfo = openFileDialog.File; if (fileinfo != null)
{
WebClient webclient = new WebClient(); string uploadFileName = fileinfo.Name.ToString(); //获取所选文件的名字 #region 把文件上传到服务器上 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/form-data";//"application/x-www-form-urlencoded";// webclient.OpenWriteAsync(upTargetUri, "POST", fileinfo.OpenRead());
webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed); #endregion }
else
{
MessageBox.Show("请选取想要上载的图片!!!");
}
} }
void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{ //将图片数据流发送到服务器上 // e.UserState - 需要上传的流(客户端流)
Stream clientStream = e.UserState as Stream;
// e.Result - 目标地址的流(服务端流)
Stream serverStream = e.Result;
byte[] buffer = new byte[clientStream.Length];
int readcount = ;
// clientStream.Read - 将需要上传的流读取到指定的字节数组中
while ((readcount = clientStream.Read(buffer, , buffer.Length)) > )
{
// serverStream.Write - 将指定的字节数组写入到目标地址的流
serverStream.Write(buffer, , 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.ToString());
}
else
{
System.Windows.Browser.HtmlPage.Window.Alert("文件上传成功!!!");
}
}
 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web; namespace SilverlightApplication9.Web
{
/// <summary>
/// WebClientUpLoadStreamHandler 的摘要说明
/// </summary>
public class WebClientUpLoadStreamHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
//获取上传的数据流
string fileNameStr = context.Request.QueryString["fileName"]; Stream sr = context.Request.InputStream;
try
{
string filename = ""; filename = fileNameStr; byte[] buffer = new byte[];
int bytesRead = ;
//将当前数据流写入服务器端文件夹ClientBin下
string targetPath = context.Server.MapPath("Pics/" + filename); using (FileStream fs = File.Create(targetPath, ))
{
while ((bytesRead = sr.Read(buffer, , buffer.Length)) > )
{
//向文件中写信息
fs.Write(buffer, , bytesRead);
}
} context.Response.ContentType = "text/plain";
context.Response.Write("上传成功");
}
catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write("上传失败, 错误信息:" + e.Message);
}
finally
{ sr.Dispose(); } } public bool IsReusable
{
get
{
return false;
}
}
}
}

2.下载
2.1下载方法1

  #region  下载图片
SaveFileDialog sfd = null;
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
//向指定的Url发送下载流数据请求
string imgUrl = "http://localhost:51896/Pics/Wildlife.wmv";
Uri endpoint = new Uri(imgUrl);
sfd = new SaveFileDialog()
{
DefaultExt = "jpeg",
Filter = "Text files (*.jpeg)|*.jpeg|All files (*.*)|*.*",
FilterIndex =
}; if (sfd.ShowDialog() == true)
{ Uri end1point = new Uri(imgUrl);
WebClient client = new WebClient();
client.OpenReadCompleted += (ss, ee) =>
{
Stream pngStream = ee.Result;
byte[] binaryData = new Byte[pngStream.Length];
pngStream.Read(binaryData, , (int)pngStream.Length);
Stream stream = sfd.OpenFile();
stream.Write(binaryData, , binaryData.Length);
stream.Close(); };
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientDownloadStream_DownloadProgressChanged);
client.OpenReadAsync(endpoint);
} } void clientDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//DownloadProgressChangedEventArgs.ProgressPercentage - 下载完成的百分比
//DownloadProgressChangedEventArgs.BytesReceived - 当前收到的字节数
//DownloadProgressChangedEventArgs.TotalBytesToReceive - 总共需要下载的字节数
//DownloadProgressChangedEventArgs.UserState - 用户标识 this.tbMsgString.Text = string.Format("完成百分比:{0} 当前收到的字节数:{1} 资料大小:{2} ",
e.ProgressPercentage.ToString() + "%",
e.BytesReceived.ToString(),
e.TotalBytesToReceive.ToString()); } #endregion

2.2下载方法2

  private void btnDownload_Click(object sender, RoutedEventArgs e)
{
System.Windows.Browser.HtmlPage.Window.Eval("window.location.href='http://localhost:51896/download.ashx?filename=IMG_20140329_093302.jpg';");
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace SilverlightApplication9.Web
{
/// <summary>
/// download 的摘要说明
/// </summary>
public class download : IHttpHandler
{
private long ChunkSize = ;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
public void ProcessRequest(HttpContext context)
{
//string fileName = "123.jpg";//客户端保存的文件名
String fileName = context.Request.QueryString["filename"];
string filePath = context.Server.MapPath(@"Pics/IMG_20140329_093302.jpg");
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true)
{
byte[] buffer = new byte[ChunkSize];
context.Response.Clear();
System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
long dataLengthToRead = iStream.Length;//获得下载文件的总大小
context.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
while (dataLengthToRead > && context.Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, , Convert.ToInt32(ChunkSize));//读取的大小
context.Response.OutputStream.Write(buffer, , lengthRead);
context.Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
context.Response.Close();
context.Response.End();
}
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
} public bool IsReusable
{
get
{
return false;
}
}
}
}

3.删除

  private void WebClientCommand(string isDeleteParam, int sort)
{
string uploadFileName = null;
WebClient webclient = new WebClient();
Uri upTargetUri = new Uri(String.Format("http://localhost:" + HtmlPage.Document.DocumentUri.Port + "/WebClientUpLoadStreamHandler.ashx?fileName={0}&result={1}", uploadFileName, isDeleteParam), UriKind.Absolute);
webclient.UploadStringCompleted += webclient_UploadStringCompleted;
webclient.UploadStringAsync(upTargetUri,""); }
  void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error == null)
{
EasySL.Controls.Window.Alert("删除成功", this.floatePanel);
}
}
 using Huitu.Bjsq.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web; namespace EasySL.Web
{
/// <summary>
/// WebClientUpLoadStreamHandler 的摘要说明
/// </summary>
public class WebClientUpLoadStreamHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//获取上传的数据流
string fileNameStr = context.Request.QueryString["fileName"];
string paramResult = context.Request.QueryString["result"];
Stream sr = context.Request.InputStream;
try
{
string filename = "";
filename = fileNameStr;
byte[] buffer = new byte[];
int bytesRead = ;
if (!string.IsNullOrEmpty(paramResult))
{
foreach (string item in paramResult.Split('|'))
{
string paramDel = context.Server.MapPath("FileLoad/" + item);
if (File.Exists(paramDel))
{
File.Delete(paramDel);
context.Response.ContentType = "text/plain";
context.Response.Write("删除成功");
}
}
}
else
{
//将当前数据流写入服务器端文件夹ClientBin下
string targetPath = context.Server.MapPath("FileLoad/" + filename);
using (FileStream fs = File.Create(targetPath, ))
{
while ((bytesRead = sr.Read(buffer, , buffer.Length)) > )
{
//向文件中写信息
fs.Write(buffer, , bytesRead);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("上传成功");
}
} catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write("上传失败, 错误信息:" + e.Message);
}
finally
{ sr.Dispose(); }
} public bool IsReusable
{
get
{
return false;
}
}
}
}

4.对于处理上传大文件的处理

 <configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="" executionTimeout="" />
</system.web>
</configuration>

5.将程序发布在iis上注意的问题(代码是VS服务器运行正常,但是发布到IIS后上传文件总是失败。后来发现,我发布到IIS的虚拟目录,所以路径变了。)

Uri uri = new Uri(string.Format("/DataHandler.ashx?filename={0}", fileName), UriKind.Relative);

//   Uri uri = new Uri("http://localhost/SEManage/UploadImg.ashx", UriKind.Absolute);
            WebClient client = new WebClient();

将Uri中的绝对路径,修改为相对路径

6.读取文件操作(.txt)

private void SetWeather()
{
WebClient downReader = new WebClient();
downReader.Encoding = System.Text.Encoding.UTF8;
downReader.OpenReadCompleted += (s, e) =>
{
if (e.Error == null)
{
using (StreamReader reader = new StreamReader(e.Result))
{
string[] line = reader.ReadToEnd().Split('|');
}
}
}
downReader.OpenReadAsync(new Uri("../AppConfig/Weather.txt", UriKind.Relative));
}
private void WeatherDispatcherTimer()
{
//创建计时器
System.Windows.Threading.DispatcherTimer myWeatherTimer = new System.Windows.Threading.DispatcherTimer();
//创建间隔时间
myWeatherTimer.Interval = new TimeSpan(, , , );
//创建到达间隔时间后需执行的函数
myWeatherTimer.Tick += (ss, ee) =>
{
InitDataWeather();
};
myWeatherTimer.Start();
}