原地址:http://www.cnblogs.com/greenerycn/archive/2010/05/15/csharp_http_post.html

1、客户端代码 用winform写的

private void button1_Click(object sender, EventArgs e)
{
string postURL = "http://localhost:40694/test1/Handler1.ashx";
string[] files = { "F:\\1.png", "F:\\2.png" };
string str = HttpUploadFile(postURL, files);
MessageBox.Show(str);
} public string HttpUploadFile(string url, string[] files)
{
//HttpContext context
//参考http://www.cnblogs.com/greenerycn/archive/2010/05/15/csharp_http_post.html
var memStream = new MemoryStream(); // 边界符
var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 文件参数头
foreach (var item in files)
{
string filePath = item;
string fileName = Path.GetFileName(item);
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var fileHeaderBytes = Encoding.UTF8.GetBytes($"Content-Disposition: form-data; name=\"{"file"}\"; filename=\"{fileName}\"\r\nContent-Type: application/octet-stream\r\n\r\n"); // 开始拼数据
memStream.Write(beginBoundary, , beginBoundary.Length); // 文件数据
memStream.Write(fileHeaderBytes, , fileHeaderBytes.Length);
var buffer = new byte[];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, , buffer.Length)) != )
{
memStream.Write(buffer, , bytesRead);
}
fileStream.Close(); //必须得写入一个换行
byte[] bytes = Encoding.UTF8.GetBytes($"\r\n");
memStream.Write(bytes, , bytes.Length);
} //// Key-Value数据
//Dictionary<string, string> stringDict = new Dictionary<string, string>();
//stringDict.Add("len", "500");
//stringDict.Add("wid", "300");
//stringDict.Add("test1", "1"); //foreach (var item in stringDict)
//{
// string name = item.Key;
// string value = item.Value;
// byte[] bytes = Encoding.UTF8.GetBytes($"\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n");
// memStream.Write(bytes, 0, bytes.Length);
//} // 写入最后的结束边界符
var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");// 最后的结束符
memStream.Write(endBoundary, , endBoundary.Length); //写入到tempBuffer
memStream.Position = ;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, , tempBuffer.Length);
memStream.Close(); // 创建webRequest并设置属性
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.Timeout = ;
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
webRequest.ContentLength = tempBuffer.Length; var requestStream = webRequest.GetRequestStream();
requestStream.Write(tempBuffer, , tempBuffer.Length);
requestStream.Close(); var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
string responseContent;
using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
responseContent = httpStreamReader.ReadToEnd();
} httpWebResponse.Close();
webRequest.Abort(); return responseContent;
}

2、服务端代码

 public class Handler1 : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; string strFileNames = "";
if (context.Request.Files.Count > )
{
for (int i = ; i < context.Request.Files.Count; i++)
{
HttpPostedFile _HttpPostedFile = context.Request.Files[i];
strFileNames += _HttpPostedFile.FileName + ",";
_HttpPostedFile.SaveAs(context.Server.MapPath($"./{_HttpPostedFile.FileName}"));
}
//context.Response.Write($"files:{context.Request.Files.Count} filenames:{strFileNames}");
}
//context.Response.Write(context.Request.Form["len"]);
//context.Response.Write(JsonConvert.SerializeObject(context.Request.Form.AllKeys.Length.ToString()));
context.Response.Write(strFileNames);
} public bool IsReusable
{
get
{
return false;
}
}
}

最新文章

  1. Linux定时,计划任务cron
  2. mac os x 连不上android 手机
  3. 检索 COM 类工厂中 CLSID 为 {} 的组件时失败,原因是出现以下错误: 80070005
  4. COJ 1002 WZJ的数据结构(二)(splay模板)
  5. There is already an open DataReader associated with this Connection which must be closed first
  6. PocketSphinx语音识别系统语言模型的训练和声学模型的改进
  7. Oracle Database 10g Express Edition系统文件损坏的解决办法
  8. precmd:6: job table full or recursion limit exceeded
  9. 使用Netty实现HTTP服务器
  10. varnish学习以及CDN的原理
  11. springboot项目屏蔽mq或者mongodb的监控日志输出
  12. IDEA永久激活方法
  13. ubuntu16.04彻底删除nginx+php
  14. Java线程池理解及用法
  15. bootstraptable学习(2)分页
  16. 代码面试集锦 1 - Uber
  17. PHP-深入学习Smarty
  18. SQL注入与安全防护---以PHP为例
  19. asp.net下使用Cookie保存登录信息
  20. 2014-04-17-网易有道-研发类-笔试题&amp;amp;參考答案

热门文章

  1. python-docx编辑word表格
  2. mysql:视图,触发器,事务,存储过程,函数。
  3. [UnityShader基础]02.深度测试 &amp; 深度写入
  4. 学生管理系统.JavaScript
  5. replace 使用正则
  6. tkinter面板切换
  7. 《算法》第五章部分程序 part 3
  8. OpenCV:直线拟合——cv::fitLine()详解
  9. Ajax 要点
  10. Human Interface Device (HID) Class Decoder