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

2019-12-30 11:12:34于丽

新建download.ashx

 

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