原地址: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;
}
}
}

C# 模拟多文件上传的更多相关文章

  1. iframe 模拟ajax文件上传and formdata ajax 文件上传

    对于文件上传 有好多种方式,一直想总结 文件上传的方法 今天就来写下 iframe  的文件上传的代码 本人语言表达能里有限,不多说了 直接上代码. 首先看 总体页面. 总共就三个文件. 实际上也就是 ...

  2. python模拟浏览器文件上传,csrf放行

    服务器端视图函数 from django.shortcuts import render,HttpResponse from django.views.decorators.csrf import c ...

  3. AJAX-----11iframe模拟ajax文件上传效果原理3

    如果直接给用户提示上传成功,那么如果用户上传的文件比较大点,那么等上半天都没反映,那么用户很有可能会刷新或者关了从来等... 那么会给我们服务器带来一定的影响,所以我们可以对这方面的用户体验度进行提升 ...

  4. AJAX-----09iframe模拟ajax文件上传效果原理1

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. AJAX-----10iframe模拟ajax文件上传效果原理2

    在实际开发中其实我们可以给用户一些提示,比如上传成功或者上传失败,废话不多说,走码: <!DOCTYPE html> <html lang="en"> &l ...

  6. 在WebBrowser中通过模拟键盘鼠标操控网页中的文件上传控件(转)

    引言 这两天沉迷了Google SketchUp,刚刚玩够,一时兴起,研究了一下WebBrowser. 我在<WebBrowser控件使用技巧分享>一文中曾谈到过“我现在可以通过WebBr ...

  7. Python模拟HTTP Post上传文件

    使用urllib2模块构造http post数据结构,提交有文件的表单(multipart/form-data),本示例提交的post表单带有两个参数及一张图片,代码如下: #buld post bo ...

  8. Netty学习笔记(一):接收nodejs模拟表单上传的文件

    好久不写博客了,也好久不写代码了,这两天临时遇上一个事情,觉得不难,加上觉得手有些生,就动手做了一下,结果遇上了不少坑,有新坑,有老坑,痛苦无比,现在总算差不多了,赶紧记录下来,希望以后不再重复这种痛 ...

  9. layui文件上传进度条(模拟)

    1.修改上传组件js(没测) https://blog.csdn.net/weixin_42457316/article/details/81017471 https://www.cnblogs.co ...

随机推荐

  1. php数组和部分操作函数

    1. 数组定义 数组的定义使用 array()方式定义,可以定义空数组: <?php $number = array(1,3,5,7,9); //定义空数组 $result = array(); ...

  2. JMeter性能(压力)测试--使用解锁

    1. 首先去官网下载JMeter:  http://jmeter.apache.org/download_jmeter.cgi 2. 解压缩后到目录 \apache-jmeter-5.0\bin 下找 ...

  3. 安全测试6_Web安全工具第二节(代理抓包分析工具)

    上节课讲了浏览器及扩展,这节课继续来学习下抓包分析. 首先看下下图,了解下代理工具的原理:代理就相当于收费站一样,任何要通过的车辆必须经过它. 浏览器的代理我们可以通过设置进行手动设置代理,或者通过P ...

  4. oracle数据库tns配置方法详解

    TNS简要介绍与应用 Oracle中TNS的完整定义:transparence Network Substrate透明网络底层,监听服务是它重要的一部分,不是全部,不要把TNS当作只是监听器. TNS ...

  5. JAVA 操作mysql 存储 调用

    HashMap map = new HashMap(); map.put("a", 9); map.put("b", ""); List&l ...

  6. 43.scrapy爬取链家网站二手房信息-1

    首先分析:目的:采集链家网站二手房数据1.先分析一下二手房主界面信息,显示情况如下: url = https://gz.lianjia.com/ershoufang/pg1/显示总数据量为27589套 ...

  7. 22.纯 CSS 创作出美丽的彩虹条纹文字

    原文地址:https://segmentfault.com/a/1190000014858628 感想: 利用四个span的::before 和 ::after创出多个WEB,给其颜色,绝对定位,再利 ...

  8. HTTP 416

    真是活久见, 竟然遇到了HTTP 416 参照 http://baike.baidu.com/view/1790469.htm , Requested Range Not Satisfiable 如果 ...

  9. webapi_uploadfile_gdal_to_geojson_and_unzipfile

    using ICSharpCode.SharpZipLib.Zip; using OSGeo.GDAL; using OSGeo.OGR; using System; using System.Col ...

  10. JAVA项目常用异常处理情况

    Java异常处理 网络整理 这里是异常的说明: 算术异常类:ArithmeticExecption 空指针异常类:NullPointerException 类型强制转换异常:ClassCastExce ...