首页 > 编程 > C# > 正文

Silverlight文件上传下载实现方法(下载保存)

2019-10-29 21:36:24
字体:
来源:转载
供稿:网友

这篇文章主要介绍了Silverlight文件上传下载实现方法(下载保存) ,需要的朋友可以参考下

search了非常多的文章,总算勉强实现了。有许多不完善的地方。

在HCLoad.Web项目下新建目录Pics复制一张图片到根目录下。

图片名:Bubble.jpg 右击->属性->生成操作:Resource

UC_UpDown.xaml

 

 
  1. <UserControl x:Class="HCLoad.UC_UpDown" 
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  4. Width="500" Height="500"
  5. <StackPanel Background="White" Height="450"
  6. <Button Content="down" Click="Button_Click"></Button> 
  7. <HyperlinkButton Content="下载保存" NavigateUri="http://localhost:4528/download.ashx?fileName=aa.txt" TargetName="_self" x:Name="lBtnDown" /> 
  8. <TextBlock x:Name="tbMsgString" Text="下载进度" TextAlignment="Center" Foreground="Green"></TextBlock> 
  9. <Button x:Name="btnDownload" Content="DownLoad Pictures" Width="150" Height="35" Margin="15" Click="btnDownload_Click"/> 
  10. <Border Background="Wheat" BorderThickness="5" Width="400" Height="280"
  11. <Image x:Name="imgDownLoad" Width="400" Height="300" Margin="15" Stretch="Fill"/> 
  12. </Border> 
  13. <Button x:Name="btnUpLoad" Content="UpLoad Pictures" Width="150" Height="35" Margin="15" Click="btnUpLoad_Click"/> 
  14. </StackPanel> 
  15. </UserControl> 

UC_UpDown.xaml.cs

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Net; 
  5. using System.Windows; 
  6. using System.Windows.Controls; 
  7. using System.Windows.Documents; 
  8. using System.Windows.Input; 
  9. using System.Windows.Media; 
  10. using System.Windows.Media.Animation; 
  11. using System.Windows.Shapes; 
  12.  
  13. using System.Windows.Media.Imaging; //因为要使用BitmapImage 
  14. using System.IO; //因为要使用Stream 
  15.  
  16. namespace HCLoad 
  17. public partial class UC_UpDown : UserControl 
  18. //1、WebClient 对象一次只能启动一个请求。如果在一个请求完成(包括出错和取消)前,即IsBusy为true时,进行第二个请求,则第二个请求将会抛出 NotSupportedException 类型的异常 
  19. //2、如果 WebClient 对象的 BaseAddress 属性不为空,则 BaseAddress 与 URI(相对地址) 组合在一起构成绝对 URI 
  20. //3、WebClient 类的 AllowReadStreamBuffering 属性:是否对从 Internet 资源接收的数据做缓冲处理。默认值为true,将数据缓存在客户端内存中,以便随时被应用程序读取 
  21.  
  22.  
  23.  
  24. //获取选定图片信息 
  25. System.IO.FileInfo fileinfo; 
  26. public UC_UpDown() 
  27. InitializeComponent(); 
  28. #region 下载图片 
  29. private void btnDownload_Click(object sender, RoutedEventArgs e) 
  30. //向指定的Url发送下载流数据请求  
  31. String imgUrl = "http://localhost:4528/Bubble.jpg"
  32. Uri endpoint = new Uri(imgUrl); 
  33.  
  34. WebClient client = new WebClient(); 
  35. client.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted); 
  36. client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientDownloadStream_DownloadProgressChanged); 
  37. client.OpenReadAsync(endpoint); 
  38. void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
  39.  
  40. //OpenReadCompletedEventArgs.Error - 该异步操作期间是否发生了错误 
  41. //OpenReadCompletedEventArgs.Cancelled - 该异步操作是否已被取消 
  42. //OpenReadCompletedEventArgs.Result - 下载后的 Stream 类型的数据 
  43. //OpenReadCompletedEventArgs.UserState - 用户标识 
  44.  
  45. if (e.Error != null
  46. MessageBox.Show(e.Error.ToString()); 
  47. return
  48. if (e.Cancelled != true
  49. //获取下载的流数据(在此处是图片数据)并显示在图片控件中 
  50. //Stream stream = e.Result; 
  51. //BitmapImage bitmap = new BitmapImage(); 
  52. //bitmap.SetSource(stream); 
  53. //imgDownLoad.Source = bitmap; 
  54. Stream clientStream = e.UserState as Stream; 
  55. Stream serverStream = (Stream)e.Result; 
  56. byte[] buffer = new byte[serverStream.Length]; 
  57. serverStream.Read(buffer, 0, buffer.Length); 
  58. clientStream.Write(buffer, 0, buffer.Length); 
  59. clientStream.Close(); 
  60. serverStream.Close(); 
  61.  
  62.  
  63.  
  64.  
  65.  
  66. void clientDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
  67. //DownloadProgressChangedEventArgs.ProgressPercentage - 下载完成的百分比 
  68. //DownloadProgressChangedEventArgs.BytesReceived - 当前收到的字节数 
  69. //DownloadProgressChangedEventArgs.TotalBytesToReceive - 总共需要下载的字节数 
  70. //DownloadProgressChangedEventArgs.UserState - 用户标识 
  71.  
  72. this.tbMsgString.Text = string.Format("完成百分比:{0} 当前收到的字节数:{1} 资料大小:{2} "
  73. e.ProgressPercentage.ToString() + "%"
  74. e.BytesReceived.ToString(), 
  75. e.TotalBytesToReceive.ToString()); 
  76.  
  77.  
  78. #endregion 
  79.  
  80. #region 上传图片 
  81. private void btnUpLoad_Click(object sender, RoutedEventArgs e) 
  82. /**/ 
  83. /* 
  84. *   OpenWriteCompleted - 在打开用于上传的流完成时(包括取消操作及有错误发生时)所触发的事件 
  85. *   WriteStreamClosed - 在写入数据流的异步操作完成时(包括取消操作及有错误发生时)所触发的事件 
  86. *   UploadProgressChanged - 上传数据过程中所触发的事件。如果调用 OpenWriteAsync() 则不会触发此事件 
  87. *   Headers - 与请求相关的的标头的 key/value 对** 
  88. *   OpenWriteAsync(Uri address, string method, Object userToken) - 打开流以使用指定的方法向指定的 URI 写入数据 
  89. *     Uri address - 接收上传数据的 URI 
  90. *     string method - 所使用的 HTTP 方法(POST 或 GET) 
  91. *     Object userToken - 需要上传的数据流 
  92. */ 
  93.  
  94.  
  95. OpenFileDialog openFileDialog = new OpenFileDialog() 
  96. //弹出打开文件对话框要求用户自己选择在本地端打开的图片文件 
  97. Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*"
  98. Multiselect = false //不允许多选  
  99. }; 
  100.  
  101. if (openFileDialog.ShowDialog() == true)//.DialogResult.OK) 
  102. //fileinfo = openFileDialog.Files; //取得所选择的文件,其中Name为文件名字段,作为绑定字段显示在前端 
  103. fileinfo = openFileDialog.File; 
  104.  
  105. if (fileinfo != null
  106. WebClient webclient = new WebClient(); 
  107.  
  108. string uploadFileName = fileinfo.Name.ToString(); //获取所选文件的名字 
  109.  
  110. #region 把图片上传到服务器上 
  111.  
  112. Uri upTargetUri = new Uri(String.Format("http://localhost:4528/WebClientUpLoadStreamHandler.ashx?fileName={0}", uploadFileName), UriKind.Absolute); //指定上传地址 
  113.  
  114. webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted); 
  115. webclient.Headers["Content-Type"] = "multipart/form-data"
  116.  
  117. webclient.OpenWriteAsync(upTargetUri, "POST", fileinfo.OpenRead()); 
  118. webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed); 
  119.  
  120. #endregion 
  121.  
  122. else 
  123. MessageBox.Show("请选取想要上载的图片!!!"); 
  124.  
  125.  
  126.  
  127.  
  128. void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) 
  129.  
  130. //将图片数据流发送到服务器上 
  131.  
  132. // e.UserState - 需要上传的流(客户端流) 
  133. Stream clientStream = e.UserState as Stream; 
  134. // e.Result - 目标地址的流(服务端流) 
  135. Stream serverStream = e.Result; 
  136. byte[] buffer = new byte[4096]; 
  137. int readcount = 0; 
  138. // clientStream.Read - 将需要上传的流读取到指定的字节数组中 
  139. while ((readcount = clientStream.Read(buffer, 0, buffer.Length)) > 0) 
  140. // serverStream.Write - 将指定的字节数组写入到目标地址的流 
  141. serverStream.Write(buffer, 0, readcount); 
  142. serverStream.Close(); 
  143. clientStream.Close(); 
  144.  
  145.  
  146.  
  147. void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e) 
  148. //判断写入是否有异常 
  149. if (e.Error != null
  150. System.Windows.Browser.HtmlPage.Window.Alert(e.Error.Message.ToString()); 
  151. else 
  152. System.Windows.Browser.HtmlPage.Window.Alert("图片上传成功!!!"); 
  153. #endregion 
  154.  
  155. private void Button_Click(object sender, RoutedEventArgs e) 
  156. //这种方法搞不定,好像提示跨域操作。 
  157. //提示:错误:Unhandled Error in Silverlight Application 跨线程访问无效。 
  158. //Uri upTargetUri = new Uri(String.Format("http://localhost:4528/download.ashx?filename={0}", "123.jpg"), UriKind.Absolute); //指定上传地址 
  159. //WebRequest request = WebRequest.Create(upTargetUri); 
  160. //request.Method = "GET"; 
  161. //request.ContentType = "application/octet-stream"; 
  162. //request.BeginGetResponse(new AsyncCallback(RequestReady), request); 
  163.  
  164. //通过调用js代码下载,比较简单。 
  165. System.Windows.Browser.HtmlPage.Window.Eval("window.location.href='http://localhost:4528/download.ashx?filename=123.jpg';"); 
  166. void RequestReady(IAsyncResult asyncResult) 
  167. MessageBox.Show("RequestComplete"); 
  168.  

在HCLoad.Web项目下新建WebClientUpLoadStreamHandler.ashx

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Web; 
  5.  
  6. using System.IO; //因为要用到Stream 
  7.  
  8. namespace HCLoad.Web 
  9. public class WebClientUpLoadStreamHandler : IHttpHandler 
  10.  
  11. public void ProcessRequest(HttpContext context) 
  12. //获取上传的数据流 
  13. string fileNameStr = context.Request.QueryString["fileName"]; 
  14. Stream sr = context.Request.InputStream; 
  15. try 
  16. string filename = ""
  17.  
  18. filename = fileNameStr; 
  19.  
  20. byte[] buffer = new byte[4096]; 
  21. int bytesRead = 0; 
  22. //将当前数据流写入服务器端文件夹ClientBin下 
  23. string targetPath = context.Server.MapPath("Pics/" + filename + ".jpg"); 
  24. using (FileStream fs = File.Create(targetPath, 4096)) 
  25. while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0) 
  26. //向文件中写信息 
  27. fs.Write(buffer, 0, bytesRead); 
  28.  
  29. context.Response.ContentType = "text/plain"
  30. context.Response.Write("上传成功"); 
  31. catch (Exception e) 
  32. context.Response.ContentType = "text/plain"
  33. context.Response.Write("上传失败, 错误信息:" + e.Message); 
  34. finally 
  35. { sr.Dispose(); } 
  36.  
  37.  
  38. public bool IsReusable 
  39. get 
  40. return false
  41.  

新建download.ashx

 

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

参考:

http://www.cnblogs.com/wsdj-ittech/archive/2009/08/26/1554056.html

http://www.cnblogs.com/wsdj-ittech/archive/2009/08/25/1553534.html

http://www.cnblogs.com/wmt1708/archive/2009/03/07/1405009.html

http://topic.csdn.net/u/20090918/10/5e41ab52-f514-46b5-ae6a-d69ddb197213.html

http://www.cnblogs.com/wsdj-ittech/archive/2009/08/25/1553534.html

http://www.cnblogs.com/gwazy/archive/2009/04/02/1427781.html

http://www.cnblogs.com/ewyb/archive/2009/12/10/1621020.html

http://blog.csdn.net/emily1900/archive/2010/06/08/5655726.aspx


注:相关教程知识阅读请移步到c#教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表