昨天遇到一个比较奇怪的需求,大致是需要在服务器上部署一个http服务,但是服务的具体功能不知道,以后在客服端实现。这里介绍一下系统背景,有一个系统运(部署在美国)行了很多年了,给系统产生了很多文件,现在需要把该系统的文件(依据数据库中的记录)来做相应的archive,做了后发现里面还有一些独立的文件(不与数据库记录相关),那么这时我们需要删除这些独立的文件,或者把它们remove到其他地方,需要得到这些文件的list。后来想了想以后会不会还有别的什么需求啊,所以就想做一个通用的HTTPhandler了。这里说明一下:production时在美国,Archive在香港;在我们大陆的系统权限放的都比较开,在美国那个权限管的非常紧,我们是没有权限直接操作Production上的文件,所以才需要用http 协议来做。这里的http server部署到US,而client 却部署到hk。

整个解决方案如图:

其中

WebApp项目部署到Production上(us)

ConsoleApp部署到archive上(hk)

HttpRequestLibrary 是一个对象序列化的通用类以及一个请求类的包装,WebApp和ConsoleApp都需要引用该dll

ProcessAction是在客户端实现的,但是在服务器端反序列化是必须有该文件,所以该dll将会从client 上传到Production上。

首先我们来看看服务器端的实现:

首先需要创建一个ProcessActionHandler.ashx来处理客户端的调用:

  1. public class ProcessActionHandler : IHttpHandler
  2. {
  3. public void ProcessRequest(HttpContext context)
  4. {
  5. context.Response.ContentType = "text/plain";
  6. try
  7. {
  8. string inputstring = ReadInputStream();
  9. if (!string.IsNullOrEmpty(inputstring))
  10. {
  11. HttpRequestInfo requestinfo = inputstring;
  12. if (requestinfo.Process != null)
  13. {
  14. requestinfo.Process(requestinfo);
  15. }
  16. }
  17. else
  18. {
  19. //context.Response.StatusCode = 404;
  20. context.Response.Write("input error message");
  21. }
  22. }
  23. catch (Exception ex)
  24. {
  25. context.Response.Write(ex.Message);
  26. }
  27. }
  28. private string ReadInputStream()
  29. {
  30. StringBuilder inputString = new StringBuilder();
  31. using (Stream sr = HttpContext.Current.Request.InputStream)
  32. {
  33. byte[] data = new byte[ * ];
  34. int readCount = sr.Read(data, , data.Length);
  35. while (readCount > )
  36. {
  37. string text = Encoding.UTF8.GetString(data, , readCount);
  38. inputString.Append(text);
  39. readCount = sr.Read(data, , data.Length);
  40. }
  41. }
  42. return inputString.ToString();
  43. }
  44.  
  45. public bool IsReusable
  46. {
  47. get
  48. {
  49. return false;
  50. }
  51. }
  52. }

这里的HttpRequestInfo类是客户端创建的,这里调用HttpRequestInfo的Process方法也是客户端实现的。如何才能获得客户端的实现了,我们需要把客户端实现的dll文件上传到服务器上。

所以需要创建一个UploadActionHandler.ashx来上传客户端的处理:

  1. public class UploadActionHandler : IHttpHandler
  2. {
  3. public void ProcessRequest(HttpContext context)
  4. {
  5. context.Response.ContentType = "text/plain";
  6. string baseFilePath = context.Server.MapPath("Bin");
  7. if (context.Request.Files.Count > )
  8. {
  9. try
  10. {
  11. HttpPostedFile file = context.Request.Files[];
  12. FileInfo fileInfo = new FileInfo(file.FileName);
  13. if (fileInfo.Extension.Equals(".dll"))
  14. {
  15. string tempPath = tempPath = Path.Combine(baseFilePath, fileInfo.Name);
  16. file.SaveAs(tempPath);
  17. context.Response.Write("Success");
  18. }
  19. else
  20. {
  21. context.Response.Write("Failed:\r\n There only upload dll file");
  22. }
  23. }
  24. catch (Exception ex)
  25. {
  26. context.Response.Write("Failed:\r\n" + ex.Message);
  27. }
  28. }
  29. else
  30. {
  31. context.Response.Write("Failed:\r\nThe Request has not upload file");
  32. }
  33. }
  34.  
  35. public bool IsReusable
  36. {
  37. get
  38. {
  39. return false;
  40. }
  41. }
  42. }

那么对象时如何序列化和反序列化,以及HttpRequestInfo的定义是什么样的了,这就要参考我们的HttpRequestLibrary项目了。

  1. namespace HttpRequestLibrary
  2. {
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Net;
  8. using System.Runtime.Remoting.Messaging;
  9. using System.Runtime.Serialization.Formatters.Binary;
  10. using System.Runtime.Serialization.Formatters.Soap;
  11. using System.Text;
  12. using System.Web;
  13.  
  14. public enum FormatterType
  15. {
  16. /// <summary>
  17. /// SOAP消息格式编码
  18. /// </summary>
  19. Soap,
  20.  
  21. /// <summary>
  22. /// 二进制消息格式编码
  23. /// </summary>
  24. Binary
  25. }
  26.  
  27. public static class SerializationHelper
  28. {
  29. private const FormatterType DefaultFormatterType = FormatterType.Binary;
  30.  
  31. /// <summary>
  32. /// 按照串行化的编码要求,生成对应的编码器。
  33. /// </summary>
  34. /// <param name="formatterType"></param>
  35. /// <returns></returns>
  36. private static IRemotingFormatter GetFormatter(FormatterType formatterType)
  37. {
  38. switch (formatterType)
  39. {
  40. case FormatterType.Binary: return new BinaryFormatter();
  41. case FormatterType.Soap: return new SoapFormatter();
  42. }
  43. throw new NotSupportedException();
  44. }
  45.  
  46. /// <summary>
  47. /// 把对象序列化转换为字符串
  48. /// </summary>
  49. /// <param name="graph">可串行化对象实例</param>
  50. /// <param name="formatterType">消息格式编码类型(Soap或Binary型)</param>
  51. /// <returns>串行化转化结果</returns>
  52. /// <remarks>调用BinaryFormatter或SoapFormatter的Serialize方法实现主要转换过程。
  53. /// </remarks>
  54. public static string SerializeObjectToString(object graph, FormatterType formatterType)
  55. {
  56. using (MemoryStream memoryStream = new MemoryStream())
  57. {
  58. IRemotingFormatter formatter = GetFormatter(formatterType);
  59. formatter.Serialize(memoryStream, graph);
  60. Byte[] arrGraph = memoryStream.ToArray();
  61. return Convert.ToBase64String(arrGraph);
  62. }
  63. }
  64. public static string SerializeObjectToString(object graph)
  65. {
  66. return SerializeObjectToString(graph, DefaultFormatterType);
  67. }
  68.  
  69. /// <summary>
  70. /// 把已序列化为字符串类型的对象反序列化为指定的类型
  71. /// </summary>
  72. /// <param name="serializedGraph">已序列化为字符串类型的对象</param>
  73. /// <param name="formatterType">消息格式编码类型(Soap或Binary型)</param>
  74. /// <typeparam name="T">对象转换后的类型</typeparam>
  75. /// <returns>串行化转化结果</returns>
  76. /// <remarks>调用BinaryFormatter或SoapFormatter的Deserialize方法实现主要转换过程。
  77. /// </remarks>
  78. public static T DeserializeStringToObject<T>(string graph, FormatterType formatterType)
  79. {
  80. Byte[] arrGraph = Convert.FromBase64String(graph);
  81. using (MemoryStream memoryStream = new MemoryStream(arrGraph))
  82. {
  83. IRemotingFormatter formatter = GetFormatter(formatterType);
  84. return (T)formatter.Deserialize(memoryStream);
  85. }
  86. }
  87.  
  88. public static T DeserializeStringToObject<T>(string graph)
  89. {
  90. return DeserializeStringToObject<T>(graph, DefaultFormatterType);
  91. }
  92. }
  93.  
  94. [Serializable]
  95. public class HttpRequestInfo
  96. {
  97. public HttpRequestInfo()
  98. {
  99. ContentData = new byte[0];
  100. CommData = new Dictionary<string, string>();
  101. }
  102. public byte[] ContentData { set; get; }
  103. public Action<HttpRequestInfo> Process { set; get; }
  104. public Dictionary<string, string> CommData { set; get; }
  105.  
  106. public override string ToString()
  107. {
  108. string graph = SerializationHelper.SerializeObjectToString(this);
  109. return graph;
  110. }
  111. public static implicit operator HttpRequestInfo(string contentString)
  112. {
  113. return SerializationHelper.DeserializeStringToObject<HttpRequestInfo>(contentString);
  114. }
  115. }
  116. }

那么客服端如何来操作服务器端了,需要查看ProcessAction项目的实现了:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using HttpRequestLibrary;
  8. using System.Web;
  9.  
  10. namespace ProcessAction
  11. {
  12. public class HttpCommProcess
  13. {
  14. public static bool UploadFile(string address, string fileNamePath, out string error)
  15. {
  16. try
  17. {
  18. error = string.Empty;
  19. string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
  20. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
  21.  
  22. StringBuilder sb = new StringBuilder();
  23. sb.Append("--");
  24. sb.Append(strBoundary);
  25. sb.Append("\r\n");
  26. sb.Append("Content-Disposition: form-data; name=\"");
  27. sb.Append("file");
  28. sb.Append("\"; filename=\"");
  29. sb.Append(fileNamePath);
  30. sb.Append("\"");
  31. sb.Append("\r\n");
  32. sb.Append("Content-Type: ");
  33. sb.Append(@"application\octet-stream");
  34. sb.Append("\r\n");
  35. sb.Append("\r\n");
  36. string strPostHeader = sb.ToString();
  37. byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
  38. HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
  39. httpReq.Method = "POST";
  40. httpReq.AllowWriteStreamBuffering = false;
  41.  
  42. httpReq.Timeout = 300000;
  43. httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
  44.  
  45. string responseText = string.Empty;
  46. using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
  47. {
  48. BinaryReader r = new BinaryReader(fs);
  49. httpReq.ContentLength = fs.Length + postHeaderBytes.Length + boundaryBytes.Length; ;
  50.  
  51. byte[] buffer = new byte[fs.Length];
  52. int size = r.Read(buffer, 0, buffer.Length);
  53.  
  54. using (Stream postStream = httpReq.GetRequestStream())
  55. {
  56. postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  57. postStream.Write(buffer, 0, size);
  58. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  59. }
  60. }
  61. WebResponse webRespon = httpReq.GetResponse();
  62. using (StreamReader s = new StreamReader(webRespon.GetResponseStream()))
  63. {
  64. responseText = s.ReadToEnd();
  65. }
  66. if (responseText.Contains("Success"))
  67. {
  68. return true;
  69. }
  70. else
  71. {
  72. error = "UploadFile :" + responseText;
  73. return false;
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. error = "UploadFile:" + ex.Message;
  79. return false;
  80. }
  81.  
  82. }
  83.  
  84. public static void SendHttpRequestData( string url,string reuestContent)
  85. {
  86. try
  87. {
  88. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  89. request.Method = "POST";
  90. request.ContentType = "text/xml";
  91. request.KeepAlive = false;
  92. request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
  93. using (Stream sr = request.GetRequestStream())
  94. {
  95. byte[] data = Encoding.UTF8.GetBytes(reuestContent);
  96. sr.Write(data, 0, data.Length);
  97. }
  98. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  99. if (response.StatusCode == HttpStatusCode.OK)
  100. {
  101. StringBuilder responseMessage = new StringBuilder();
  102. using (Stream sr = response.GetResponseStream())
  103. {
  104. byte[] data = new byte[1024 * 10];
  105. int readcount = sr.Read(data, 0, data.Length);
  106. while (readcount > 0)
  107. {
  108. string str = Encoding.UTF8.GetString(data, 0, readcount);
  109. responseMessage.Append(str);
  110. readcount = sr.Read(data, 0, data.Length);
  111. }
  112. Console.WriteLine(responseMessage);
  113. }
  114. }
  115. }
  116. catch (Exception ex)
  117. {
  118. Console.WriteLine(ex.Message);
  119. }
  120. }
  121.  
  122. public static string GetUploadFileContent(string filename)
  123. {
  124. HttpRequestInfo requestInfo = new HttpRequestInfo();
  125. FileInfo file = new FileInfo(filename);
  126. requestInfo.CommData.Add("FileName", file.Name);
  127. requestInfo.ContentData = new byte[file.Length];
  128. using (Stream sr = File.OpenRead(filename))
  129. {
  130. sr.Read(requestInfo.ContentData, 0, requestInfo.ContentData.Length);
  131. }
  132. requestInfo.Process = (x) =>
  133. {
  134. try
  135. {
  136. string tempfile = Path.Combine(@"c:\test", x.CommData["FileName"]);
  137. using (Stream wr = File.Open(tempfile, FileMode.OpenOrCreate, FileAccess.Write))
  138. {
  139. wr.Write(x.ContentData, 0, x.ContentData.Length);
  140. }
  141. HttpContext.Current.Response.Write("Success");
  142. }
  143. catch (Exception ex)
  144. {
  145. HttpContext.Current.Response.Write(ex.Message);
  146. }
  147.  
  148. };
  149. return requestInfo.ToString();
  150. }
  151.  
  152. public static string GetFileNames(string folderpath)
  153. {
  154. HttpRequestInfo requestInfo = new HttpRequestInfo();
  155. requestInfo.CommData.Add("FolderPath", folderpath);
  156. requestInfo.Process = (x) =>
  157. {
  158. try
  159. {
  160. DirectoryInfo dir=new DirectoryInfo( x.CommData["FolderPath"]);
  161. foreach (FileInfo item in dir.GetFiles())
  162. {
  163. HttpContext.Current.Response.Write(item.FullName+Environment.NewLine);
  164. }
  165. HttpContext.Current.Response.Write("Success");
  166. }
  167. catch (Exception ex)
  168. {
  169. HttpContext.Current.Response.Write(ex.Message);
  170. }
  171.  
  172. };
  173. return requestInfo.ToString();
  174. }
  175. }
  176. }

这里我们来看看GetFileNames方法的实现吧:

  1. public static string GetFileNames(string folderpath)
  2. {
  3. HttpRequestInfo requestInfo = new HttpRequestInfo();
  4. requestInfo.CommData.Add("FolderPath", folderpath);
  5. requestInfo.Process = (x) =>
  6. {
  7. try
  8. {
  9. DirectoryInfo dir=new DirectoryInfo( x.CommData["FolderPath"]);
  10. foreach (FileInfo item in dir.GetFiles())
  11. {
  12. HttpContext.Current.Response.Write(item.FullName+Environment.NewLine);
  13. }
  14. HttpContext.Current.Response.Write("Success");
  15. }
  16. catch (Exception ex)
  17. {
  18. HttpContext.Current.Response.Write(ex.Message);
  19. }
  20.  
  21. };
  22. return requestInfo.ToString();
  23. }
  24. }

很显然这里的Process就是服务器端将要call的回调函数。那么这个处理很显然是在客户端,服务器端如何才能识别了,就需要把该代码上传到服务器端。

那么最终客服端该如何调用该代码了:

  1. static void Main(string[] args)
  2. {
  3. string error = string.Empty;
  4. bool uploaded = HttpCommProcess.UploadFile("http://vihk2awwwdev01/webapp/UploadActionHandler.ashx", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ProcessAction.dll"), out error);
  5. if (!uploaded)
  6. {
  7. Console.WriteLine(error);
  8. }
  9. else
  10. {
  11. ///upload file
  12. string content = HttpCommProcess.GetUploadFileContent(@"C:\IPC.LOG");
  13. Console.WriteLine("Upload Fils");
  14. HttpCommProcess.SendHttpRequestData("http://vihk2awwwdev01/webapp/ProcessActionHandler.ashx", content);
  15. //get file List
  16. content = HttpCommProcess.GetFileNames(@"C:\ArchiveInfoCenter\ArchiveInfoCenter");
  17. Console.WriteLine("Get Fils List");
  18. HttpCommProcess.SendHttpRequestData("http://vihk2awwwdev01/webapp/ProcessActionHandler.ashx", content);
  19. }
  20. Console.ReadLine();
  21. }

首先上传dll文件,然后在发送http请求,运行结果如图:

客户端结果:

服务器文件上传结果(这里只能上传小文件,大文件序列化和反序列化会很慢很慢)

服务器上原文件目录:

在某种程度上我也不赞成这样做,会很危险的。这里只是纯粹从技术的角度来讲如何实现,有不好的地方还请大家拍砖。

源码下载地址:http://download.csdn.net/detail/dz45693/5856523

如何实现一个通用的IHttpHandler 万能的IHttpHandler HttpWebRequest文件上传的更多相关文章

  1. PHP封装一个通用好用的文件上传处理类

    封装一个文件上传类完成基本功能如下: 1.可上传多个或单个文件 2.上传成功返回一个或多个文件名 3.上传失败则返回每个失败文件的错误信息 上传类中的基本功能: 1.构造参数,用户可以自定义配置参数, ...

  2. 06.LoT.UI 前后台通用框架分解系列之——浮夸的图片上传

    LOT.UI分解系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#lotui LoT.UI开源地址如下:https://github.com/du ...

  3. 用Canvas+Javascript FileAPI 实现一个跨平台的图片剪切、滤镜处理、上传下载工具

    直接上代码,其中上传功能需要自己配置允许跨域的文件服务器地址~ 或者将html文件贴到您的站点下同源上传也OK. 支持: 不同尺寸图片获取. 原图缩小放大. 原图移动. 选择框大小改变. 下载选中的区 ...

  4. [转]一个文件上传的jquery插件

    http://www.jb51.net/article/51547.htm 这篇文章主要介绍了使用ajaxfileupload.js实现ajax上传文件php版,需要的朋友可以参考下     无论是P ...

  5. joomla安装插件报错:上传文件到服务器发生了一个错误。 过小的PHP文件上传尺寸

    在安装joomla的AKeeba插件的时候报错如下:上传文件到服务器发生了一个错误. 过小的PHP文件上传尺寸.解决方法是修改php.ini文件,打开文件后搜索upload_max_filesize! ...

  6. 分享一个PHP文件上传类

    该类用于处理文件上传,可以上传一个文件,也可以上传多个文件. 包括的成员属性有: private $path = "./uploads"; //上传文件保存的路径 private ...

  7. struts2一个和多个文件上传及下载

    struts2的文件上传相比我们自己利用第三方jar包(commons-fileupload-1.2.1.jar   commons-io-1.3.2.jar )要简单的多,当然struts2里面也是 ...

  8. 用VSCode开发一个asp.net core2.0+angular5项目(5): Angular5+asp.net core 2.0 web api文件上传

    第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 第二部分: http://www.cnblogs.com/cgzl/p/8481825.html 第三 ...

  9. 转:【专题十一】实现一个基于FTP协议的程序——文件上传下载器

    引言: 在这个专题将为大家揭开下FTP这个协议的面纱,其实学习知识和生活中的例子都是很相通的,就拿这个专题来说,要了解FTP协议然后根据FTP协议实现一个文件下载器,就和和追MM是差不多的过程的,相信 ...

随机推荐

  1. android 休眠唤醒机制分析(三) — suspend

    本文转自:http://blog.csdn.net/g_salamander/article/details/7988340 前面我们分析了休眠的第一个阶段即浅度休眠,现在我们继续看休眠的第二个阶段 ...

  2. 转:Google论文之三----MapReduce

    文章来自于:http://www.cnblogs.com/geekma/p/3139823.html MapReduce:大型集群上的简单数据处理 摘要 MapReduce是一个设计模型,也是一个处理 ...

  3. udp丢包原因分析

    1.  发送方没有进行频率控制(令牌桶算法),短时间内大量的包发送到server端,server端是单线程,先epoll wait,再process,就会造程process时丢掉server传过来的包 ...

  4. [转]Windows平台下安装Hadoop

    1.安装JDK1.6或更高版本 官网下载JDK,安装时注意,最好不要安装到带有空格的路径名下,例如:Programe Files,否则在配置Hadoop的配置文件时会找不到JDK(按相关说法,配置文件 ...

  5. Windows消息编程(写的不错,有前因后果)

    本文主要包括以下内容: 1.简单理解Windows的消息2.通过一个简单的Win32程序理解Windows消息3.通过几个Win32程序实例进一步深入理解Windows消息4.队列消息和非队列消息5. ...

  6. -_-#【Angular】自定义指令directive

    AngularJS学习笔记 <!DOCTYPE html> <html ng-app="Demo"> <head> <meta chars ...

  7. 海美迪Q5智能机顶盒的蓝牙功能

    虽然在硬件上,海美迪Q5智能机顶盒没有集成蓝牙模块,但是在软件系统上,Q5是支持蓝牙驱动的,所以它可以通过USB外接蓝牙适配器来扩展出蓝牙功能,简单来说,就是你另外买个蓝牙适配器,插到Q5上面,就能用 ...

  8. Robot Framework安装配置 Linux

    Simple introduction Robot Framework is a generic test automation framework for acceptance testing an ...

  9. 一个在字符串中查找多个关键字的函数strstrs(三种不同算法实现及效率分析)

    平时项目中有时需要用到在字符串中搜索两个或更多的关键字的情景.例如:将字符串"ab|cd#ef|"按竖线或者井号做分隔 如果是大项目,一般会采用正则表达式做处理.但有时写个小程序, ...

  10. 利用Jenkins自动部署工具间接构建kettle的调度平台

    关于Jenkins的介绍我就不说了,自己百度,因为这个工具调用脚本只是他的功能的冰山一角,其他功能我也不能理解,因为不是那个领域.        下面我就介绍一下为什么我们需要一个调度平台,以及学习完 ...