C# 模拟多文件上传
原地址: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# 模拟多文件上传的更多相关文章
- iframe 模拟ajax文件上传and formdata ajax 文件上传
对于文件上传 有好多种方式,一直想总结 文件上传的方法 今天就来写下 iframe 的文件上传的代码 本人语言表达能里有限,不多说了 直接上代码. 首先看 总体页面. 总共就三个文件. 实际上也就是 ...
- python模拟浏览器文件上传,csrf放行
服务器端视图函数 from django.shortcuts import render,HttpResponse from django.views.decorators.csrf import c ...
- AJAX-----11iframe模拟ajax文件上传效果原理3
如果直接给用户提示上传成功,那么如果用户上传的文件比较大点,那么等上半天都没反映,那么用户很有可能会刷新或者关了从来等... 那么会给我们服务器带来一定的影响,所以我们可以对这方面的用户体验度进行提升 ...
- AJAX-----09iframe模拟ajax文件上传效果原理1
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- AJAX-----10iframe模拟ajax文件上传效果原理2
在实际开发中其实我们可以给用户一些提示,比如上传成功或者上传失败,废话不多说,走码: <!DOCTYPE html> <html lang="en"> &l ...
- 在WebBrowser中通过模拟键盘鼠标操控网页中的文件上传控件(转)
引言 这两天沉迷了Google SketchUp,刚刚玩够,一时兴起,研究了一下WebBrowser. 我在<WebBrowser控件使用技巧分享>一文中曾谈到过“我现在可以通过WebBr ...
- Python模拟HTTP Post上传文件
使用urllib2模块构造http post数据结构,提交有文件的表单(multipart/form-data),本示例提交的post表单带有两个参数及一张图片,代码如下: #buld post bo ...
- Netty学习笔记(一):接收nodejs模拟表单上传的文件
好久不写博客了,也好久不写代码了,这两天临时遇上一个事情,觉得不难,加上觉得手有些生,就动手做了一下,结果遇上了不少坑,有新坑,有老坑,痛苦无比,现在总算差不多了,赶紧记录下来,希望以后不再重复这种痛 ...
- layui文件上传进度条(模拟)
1.修改上传组件js(没测) https://blog.csdn.net/weixin_42457316/article/details/81017471 https://www.cnblogs.co ...
随机推荐
- 关于AJAX与form表单提交数据的格式
一 form表单传输文件的格式: 只有三种: multipart/form-data 一般用于传输文件,图片文件或者其他的. 那么其中我们默认的是application/x-www-form-urle ...
- fatal error C1083: Cannot open include file: 'openssl/opensslv.h'
在安装针对ELK系统的警告工具elastalert时,报错: fatal error C1083: Cannot open include file: 'openssl/opensslv.h',如下图 ...
- [PHP-DI] 理解依赖注入
理解依赖注入 依赖注入 和 依赖注入容器 是不同的: 依赖注入 (Dependency injection) 是编写更好代码的一种方法 容器 (Container) 是帮助注入依赖关系的工具 你不需要 ...
- uuid.uuid4().hex
uuid.uuid4().hex .hex 将生成的uuid字符串中的 - 删除
- 正则表达式-使用说明Regular Expression How To (Perl, Python, etc)
notepad++ wiki about regular expression 正则表达式-使用说明Regular Expression How To (Perl, Python, etc) http ...
- mysql安装卸载-windows
安装:(注意点) 官网download安装包 choose setup type --> custom 安装路径 detailed configuration developer machin ...
- winform 之MDI容器
MDI是指将多控件窗体在同一窗体中打开 1.设置:属性中IsMDIContainer:true; 窗体变为灰色成为MDI窗体容器 2.MDI中一般采用菜单作为打开方式 3.子级窗体在MDI中打开,需先 ...
- 自定义界面上绘制Text,可通过拖动控制文字大小及其位置
项目地址 最近项目上有个需求,需要在一块区域中显示文字,这块区域可以拖动,也可以通过拖拽右下角来改变大小,里面的文字大小要根据区域的大小进行自适应.刚开始觉得这个需求不难,只需要一个TextView就 ...
- python的回调callback
python的回调callback很强大,特别是函数参数可以是kw,因为一个函数编译后对应函数对象,函数对象中包含了参数的信息,当你调用函数时,会判断传入参数是否正确.通过导入模块,可以使用模块中的函 ...
- linux centos7.5修改主机名和ip永久生效
以centos7.5为例 1.修改主机名 [root@localhost ~]# hostname localhost.localdomain[root@localhost ~]# hostname ...