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

1.上传

 1  private void Button_Click_1(object sender, RoutedEventArgs e)
 2         {
 3             OpenFileDialog openFileDialog = new OpenFileDialog()
 4              {  //弹出打开文件对话框要求用户自己选择在本地端打开的图片文件
 5                  Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*",
 6                  Multiselect = false  //不允许多选 
 7              };
 8 
 9             if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
10             {
11                 //fileinfo = openFileDialog.Files; //取得所选择的文件,其中Name为文件名字段,作为绑定字段显示在前端
12                 FileInfo fileinfo = openFileDialog.File;
13 
14                 if (fileinfo != null)
15                 {
16                     WebClient webclient = new WebClient();
17 
18                     string uploadFileName = fileinfo.Name.ToString(); //获取所选文件的名字
19 
20                     #region 把文件上传到服务器上
21 
22                     Uri upTargetUri = new Uri(String.Format("http://localhost:" + HtmlPage.Document.DocumentUri.Port + "/WebClientUpLoadStreamHandler.ashx?fileName={0}", uploadFileName), UriKind.Absolute); //指定上传处理程序
23 
24                     webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
25                     webclient.Headers["Content-Type"] = "multipart/form-data";//"application/x-www-form-urlencoded";// 
26 
27                     webclient.OpenWriteAsync(upTargetUri, "POST", fileinfo.OpenRead());
28                     webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed);
29 
30                     #endregion
31 
32                 }
33                 else
34                 {
35                     MessageBox.Show("请选取想要上载的图片!!!");
36                 }
37             }
38 
39         }
40         void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
41         {
42 
43             //将图片数据流发送到服务器上
44 
45             // e.UserState - 需要上传的流(客户端流)
46             Stream clientStream = e.UserState as Stream;
47             // e.Result - 目标地址的流(服务端流)
48             Stream serverStream = e.Result;
49             byte[] buffer = new byte[clientStream.Length];
50             int readcount = 0;
51             // clientStream.Read - 将需要上传的流读取到指定的字节数组中
52             while ((readcount = clientStream.Read(buffer, 0, buffer.Length)) > 0)
53             {
54                 // serverStream.Write - 将指定的字节数组写入到目标地址的流
55                 serverStream.Write(buffer, 0, readcount);
56             }
57             serverStream.Close();
58             clientStream.Close();
59         }
60         void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
61         {
62             //判断写入是否有异常
63             if (e.Error != null)
64             {
65                 System.Windows.Browser.HtmlPage.Window.Alert(e.Error.Message.ToString());
66             }
67             else
68             {
69                 System.Windows.Browser.HtmlPage.Window.Alert("文件上传成功!!!");
70             }
71         }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Web;
 6 
 7 namespace SilverlightApplication9.Web
 8 {
 9     /// <summary>
10     /// WebClientUpLoadStreamHandler 的摘要说明
11     /// </summary>
12     public class WebClientUpLoadStreamHandler : IHttpHandler
13     {
14 
15         public void ProcessRequest(HttpContext context)
16         {
17             //获取上传的数据流
18             string fileNameStr = context.Request.QueryString["fileName"];
19              
20             Stream sr = context.Request.InputStream;
21             try
22             {
23                 string filename = "";
24 
25                 filename = fileNameStr;
26 
27                 byte[] buffer = new byte[4096];
28                 int bytesRead = 0;
29                 //将当前数据流写入服务器端文件夹ClientBin下
30                 string targetPath = context.Server.MapPath("Pics/" + filename);
31                
32                 using (FileStream fs = File.Create(targetPath, 4096))
33                 {
34                     while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
35                     {
36                         //向文件中写信息
37                         fs.Write(buffer, 0, bytesRead);
38                     }
39                 }
40 
41                 context.Response.ContentType = "text/plain";
42                 context.Response.Write("上传成功");
43             }
44             catch (Exception e)
45             {
46                 context.Response.ContentType = "text/plain";
47                 context.Response.Write("上传失败, 错误信息:" + e.Message);
48             }
49             finally
50             { sr.Dispose(); }
51 
52         }
53 
54         public bool IsReusable
55         {
56             get
57             {
58                 return false;
59             }
60         }
61     }
62 }
View Code

2.下载
2.1下载方法1

 1  #region  下载图片
 2         SaveFileDialog sfd = null;
 3         private void btnDownload_Click(object sender, RoutedEventArgs e)
 4         {
 5             //向指定的Url发送下载流数据请求 
 6             string imgUrl = "http://localhost:51896/Pics/Wildlife.wmv";
 7             Uri endpoint = new Uri(imgUrl);
 8             sfd = new SaveFileDialog()
 9             {
10                 DefaultExt = "jpeg",
11                 Filter = "Text files (*.jpeg)|*.jpeg|All files (*.*)|*.*",
12                 FilterIndex = 2
13             };
14 
15             if (sfd.ShowDialog() == true)
16             {
17 
18                 Uri end1point = new Uri(imgUrl);
19                 WebClient client = new WebClient();
20                 client.OpenReadCompleted += (ss, ee) =>
21                 {
22                     Stream pngStream = ee.Result;
23                     byte[] binaryData = new Byte[pngStream.Length];
24                     pngStream.Read(binaryData, 0, (int)pngStream.Length);
25                     Stream stream = sfd.OpenFile();
26                     stream.Write(binaryData, 0, binaryData.Length);
27                     stream.Close();
28 
29                 };
30                 client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientDownloadStream_DownloadProgressChanged);
31                 client.OpenReadAsync(endpoint);
32             }
33 
34         }
35 
36         void clientDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
37         {
38             //DownloadProgressChangedEventArgs.ProgressPercentage - 下载完成的百分比
39             //DownloadProgressChangedEventArgs.BytesReceived - 当前收到的字节数
40             //DownloadProgressChangedEventArgs.TotalBytesToReceive - 总共需要下载的字节数
41             //DownloadProgressChangedEventArgs.UserState - 用户标识
42 
43             this.tbMsgString.Text = string.Format("完成百分比:{0} 当前收到的字节数:{1} 资料大小:{2} ",
44               e.ProgressPercentage.ToString() + "%",
45               e.BytesReceived.ToString(),
46               e.TotalBytesToReceive.ToString());
47 
48         }
49 
50         #endregion
View Code

2.2下载方法2

1  private void btnDownload_Click(object sender, RoutedEventArgs e)
2         {
3             System.Windows.Browser.HtmlPage.Window.Eval("window.location.href='http://localhost:51896/download.ashx?filename=IMG_20140329_093302.jpg';");
4 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace SilverlightApplication9.Web
 7 {
 8     /// <summary>
 9     /// download 的摘要说明
10     /// </summary>
11     public class download : IHttpHandler
12     {
13         private long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
14         public void ProcessRequest(HttpContext context)
15         {
16             //string fileName = "123.jpg";//客户端保存的文件名
17             String fileName = context.Request.QueryString["filename"];
18             string filePath = context.Server.MapPath(@"Pics/IMG_20140329_093302.jpg");
19             System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
20             
21             if (fileInfo.Exists == true)
22             {
23                 byte[] buffer = new byte[ChunkSize];
24                 context.Response.Clear();
25                 System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
26                 long dataLengthToRead = iStream.Length;//获得下载文件的总大小
27                 context.Response.ContentType = "application/octet-stream";
28                 //通知浏览器下载文件而不是打开
29                 context.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
30                 while (dataLengthToRead > 0 && context.Response.IsClientConnected)
31                 {
32                     int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
33                     context.Response.OutputStream.Write(buffer, 0, lengthRead);
34                     context.Response.Flush();
35                     dataLengthToRead = dataLengthToRead - lengthRead;
36                 }
37                 context.Response.Close();
38                 context.Response.End();
39             }
40             //context.Response.ContentType = "text/plain";
41             //context.Response.Write("Hello World");
42         }
43 
44         public bool IsReusable
45         {
46             get
47             {
48                 return false;
49             }
50         }
51     }
52 }
View Code

3.删除

 1  private void WebClientCommand(string isDeleteParam, int sort)
 2         {
 3             string uploadFileName = null;
 4             WebClient webclient = new WebClient();
 5                            Uri upTargetUri = new Uri(String.Format("http://localhost:" + HtmlPage.Document.DocumentUri.Port + "/WebClientUpLoadStreamHandler.ashx?fileName={0}&result={1}", uploadFileName, isDeleteParam), UriKind.Absolute);
 6                 webclient.UploadStringCompleted += webclient_UploadStringCompleted;
 7                 webclient.UploadStringAsync(upTargetUri,"");
 8             
 9 
10            
11         }
View Code
1  void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
2         {
3             if (e.Error == null)
4             {
5                 EasySL.Controls.Window.Alert("删除成功", this.floatePanel);  
6             }
7         }
View Code
 1 using Huitu.Bjsq.Service;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.IO;
 5 using System.Linq;
 6 using System.Web;
 7 
 8 namespace EasySL.Web
 9 {
10     /// <summary>
11     /// WebClientUpLoadStreamHandler 的摘要说明
12     /// </summary>
13     public class WebClientUpLoadStreamHandler : IHttpHandler
14     {
15         public void ProcessRequest(HttpContext context)
16         {
17             //获取上传的数据流
18             string fileNameStr = context.Request.QueryString["fileName"];
19             string paramResult = context.Request.QueryString["result"];
20             Stream sr = context.Request.InputStream;
21             try
22             {
23                 string filename = "";
24                 filename = fileNameStr;
25                 byte[] buffer = new byte[4096];
26                 int bytesRead = 0;
27                 if (!string.IsNullOrEmpty(paramResult))
28                 {
29                     foreach (string item in paramResult.Split('|'))
30                     {
31                         string paramDel = context.Server.MapPath("FileLoad/" + item);
32                         if (File.Exists(paramDel))
33                         {
34                             File.Delete(paramDel);
35                             context.Response.ContentType = "text/plain";
36                             context.Response.Write("删除成功");
37                         }
38                     }
39                 }
40                 else
41                 {
42                     //将当前数据流写入服务器端文件夹ClientBin下
43                     string targetPath = context.Server.MapPath("FileLoad/" + filename);
44                     using (FileStream fs = File.Create(targetPath, 4096))
45                     {
46                         while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
47                         {
48                             //向文件中写信息
49                             fs.Write(buffer, 0, bytesRead);
50                         }
51                     }
52                     context.Response.ContentType = "text/plain";
53                     context.Response.Write("上传成功");
54                 }
55             }
56 
57             catch (Exception e)
58             {
59                 context.Response.ContentType = "text/plain";
60                 context.Response.Write("上传失败, 错误信息:" + e.Message);
61             }
62             finally
63             { sr.Dispose(); }
64         }
65 
66         public bool IsReusable
67         {
68             get
69             {
70                 return false;
71             }
72         }
73     }
74 }
View Code

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

1 <configuration>
2     <system.web>
3       <compilation debug="true" targetFramework="4.5" />
4       <httpRuntime targetFramework="4.5" maxRequestLength="21048576" executionTimeout="7200" />
5     </system.web>
6 </configuration>
View Code

 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(0, 3, 0, 0);
            //创建到达间隔时间后需执行的函数    
            myWeatherTimer.Tick += (ss, ee) =>
            {
                InitDataWeather();
            };
            myWeatherTimer.Start();
        }
原文地址:https://www.cnblogs.com/zxbzl/p/3747546.html