FileDownload.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web;
  6. using System.Net;
  7. namespace Bowin.Common
  8. {
  9. public class FileDownload : IHttpHandler
  10. {
  11. public bool IsReusable
  12. {
  13. get { return true; }
  14. }
  15. public void ProcessRequest(HttpContext context)
  16. {
  17. context.Response.Clear();
  18. string vfilepath = context.Request.QueryString["url"].Trim();
  19. if (string.IsNullOrEmpty(vfilepath))
  20. {
  21. context.Response.StatusCode = 404;
  22. return;
  23. }
  24. var isURL = (vfilepath.ToLower().StartsWith(@"http://") || vfilepath.ToLower().StartsWith(@"https://"));
  25. string filepath = context.Server.MapPath(isURL ? @"Doc\TempFile\" + Guid.NewGuid() : vfilepath);
  26. if (isURL)
  27. {
  28. WebClient wc = new WebClient();
  29. wc.DownloadFile(vfilepath, filepath);
  30. }
  31. else if (!System.IO.File.Exists(filepath))
  32. {
  33. context.Response.StatusCode = 404;
  34. return;
  35. }
  36. string filename = context.Request.QueryString["filename"] ?? System.IO.Path.GetFileName(filepath);
  37. context.Response.ContentType = "application/octet-stream;charset=GB2312";
  38. //context.Response.Charset = "GB2312";
  39. context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + context.Server.UrlEncode(filename));
  40. context.Response.WriteFile(filepath);
  41. context.Response.Flush();
  42. }
  43. }
  44. }