国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > 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#教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 贡嘎县| 康平县| 兴安县| 军事| 苏尼特右旗| 精河县| 长垣县| 项城市| 定日县| 呼伦贝尔市| 大埔区| 乐亭县| 乌兰浩特市| 循化| 苗栗市| 正镶白旗| 阿图什市| 岱山县| 汾阳市| 探索| 武城县| 西丰县| 凌海市| 周至县| 呼和浩特市| 广汉市| 正定县| 平定县| 厦门市| 黔江区| 齐河县| 神池县| 五大连池市| 方城县| 上栗县| 洱源县| 繁峙县| 高清| 龙口市| 盐源县| 磐石市|