原地址: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. servlet为什么会出现?servlet有什么作用?

    在面试中遇到了这个问题,所以想总结一下,所以上网找了一下,主要是网上的一些我觉得比较合理的解释: servlet为什么会出现? Servlet = Service + Applet,表示小服务程序.S ...

  2. Linux性能优化 第七章 性能工具:网络

    7.1 网络I/O介绍 Linux和其他主流操作系统中的网络流量被抽象为一系列的硬件和软件层次. 链路层,也就是最低的一层,包含网络硬件,如以太网设备.在传送网络流量时,这一层并不区分流量类型,而仅仅 ...

  3. 第一类对象-> 函数名 -> 变量名

    函数对象对象可以像变量一样进行赋值 还可以作为列表的元素进行使用 可以作为返回值返回 可以作为参数进行传递 # def fn(): # print("我叫fn") # fn() # ...

  4. WPF TextBlock文子超出在最后加上省略号

    加上这个属性:TextTrimming="CharacterEllipsis" <TextBlock Text="{Binding filepaths}" ...

  5. WPF Image Source 设置相对路径图片

    BitmapImage bt = new BitmapImage(new Uri("Images\\3_u10484.png", UriKind.Relative));this.I ...

  6. nginx安装以及常用配置

    nginx的源码安装 0 安装相关软件:yum -y install pcre-devel zlib-devel openssl-devel 1 下载 nginx-1.14.0.tar.gz 2 安装 ...

  7. spring揭密学习笔记(2)-spring ioc容器:IOC的基本概念

    1. IoC的理念就是,让别人为你服务!2. 其实IoC就这么简单!原来是需要什么东西自己去拿,现在是需要什么东西就让别人送过来.一个生动的示例 3.三种依赖注入的方式 IoC模式最权威的总结和解释, ...

  8. LeetCode 12. Integer to RomanLeetCode

    整数转罗马数字 first submission import math class Solution: def __init__(self): self.roman={1:'I',5:'V',10: ...

  9. [Unity工具]批量修改字体

    效果图: using System.IO; using System.Text; using UnityEditor; using UnityEngine; using UnityEngine.UI; ...

  10. python中的find、rfind、index、rindex

    find()从左向右寻找子序列的位置,如存在多个相同子序列只返回第一个查找到的位置,如果子序列不存在返回-1 rfind()从右向左寻找子序列的位置..... index()从左向右寻找子序列的位置, ...