1.整理HttpWebRequest上传多文件和多参数。较上一个版本,更具普适性和简易型。注意(服务方web.config中要配置)这样就可以上传大文件了

<system.webServer>
<requestFiltering>
<requestLimits maxAllowedContentLength="4294967295" />
</requestFiltering>
</system.webServer>
<system.web>
<httpRuntime maxRequestLength="2048000"/>
</system.web>

2.HttpWebRequest的封装

  /// <summary>
/// Http上传文件类 - HttpWebRequest封装
/// </summary>
public class HttpUploadClient
{
public static string ExecuteMultipartRequest(string url, List<KeyValue> nvc)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.RelativeOrAbsolute));
webRequest.Method = "POST";
webRequest.Timeout = 1800000;
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
webRequest.KeepAlive = true;
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (var rs = webRequest.GetRequestStream())
{
// 普通参数模板
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
//带文件的参数模板
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
foreach (KeyValue keyValue in nvc)
{
//如果是普通参数
if (keyValue.FilePath == null)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, keyValue.Key, keyValue.Value);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
//如果是文件参数,则上传文件
else
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format(headerTemplate, keyValue.Key, keyValue.Value, keyValue.ContentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
using (var fileStream = new FileStream(keyValue.FilePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[4096];
int bytesRead = 0;
long total = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
total += bytesRead;
}
}
} }
byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
} // 获取响应
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string body = reader.ReadToEnd();
reader.Close();
return body;
}
}
}

3.参数封装(支持普通参数和多文件)

  public class KeyValue
{
public string Key;
public string Value;
public string FilePath;
public string ContentType = "*/*";
public KeyValue(string key, string value, string filePath, string contentType)
{
Key = key;
Value = value;
FilePath = filePath;
ContentType = contentType;
}
public KeyValue() { }
public KeyValue(string key, string value, string filePath)
{
Key = key;
Value = value;
FilePath = filePath;
}
public KeyValue(string key, string value)
{
Key = key;
Value = value;
}
}

4.调用示例

            List<KeyValue> keyValues = new List<KeyValue>();
keyValues.Add(new KeyValue("key1", "12_423232523"));
keyValues.Add(new KeyValue("key2", " 1 2 3"));
keyValues.Add(new KeyValue("file1", "1.img", @"C:\临时\tempDB\1.img"));
keyValues.Add(new KeyValue("file2", "2.xls", @"C:\临时\tempDB\2.xls"));
HttpUploadClient.ExecuteMultipartRequest(url, keyValues);

5.服务接收方示例

  for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
  {
HttpPostedFile file = HttpContext.Current.Request.Files[i];
file.SaveAs(""+file.FileName);
  }
  string Params = HttpContext.Current.Request.Form["key1"];

  

HttpWebRequest上传多文件和多参数——整理的更多相关文章

  1. C# HttpWebRequest 后台调用接口上传大文件以及其他参数

    直接上代码,包各位看客能用!!! 1.首先请求参数的封装 /// <summary> /// 上传文件 - 请求参数类 /// </summary> public class ...

  2. HTTP上传大文件的注意点

    使用HttpWebRequest上传大文件时,服务端配置中需要进行以下节点配置: <system.web> <compilation debug="true" t ...

  3. 【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端

    原文地址:http://docode.top/Article/Detail/10002 目录: 1.Http协议上传文件(以图片为例)请求报文体内容格式 2.完整版HttpWebRequest模拟上传 ...

  4. C#在WinForm下使用HttpWebRequest上传文件

    转自:http://blog.csdn.net/shihuan10430049/article/details/3734398 这段时间因项目需要,要实现WinForm下的文件上传,个人觉得采用FTP ...

  5. 关于HttpWebRequest上传文件

    我们web 操作离不开 http请求响应 HttpWebRequest上传文件也是一样的道理 下面码一些代码: private void UploadFile(string strRequestUri ...

  6. [转]C#在WinForm下使用HttpWebRequest上传文件并显示进度

    /// <summary> /// 将本地文件上传到指定的服务器(HttpWebRequest方法) /// </summary> /// <param name=&qu ...

  7. web大文件上传控件-设置附加参数-Xproer.HttpUploader6

    自定义附加字段在up6.js中定义,也可以不用定义: 注意: 1.附加字段必须是字符串类型. 2.如果附加字段的值包含中文,在上传前必须使用encodeURIComponent进行编码.     在引 ...

  8. PHP代码中使用post参数上传大文件

    今天连续碰到了两个同事向我反应上传大文件(8M)失败的事情! 都是在PHP代码中通常使用post参数进行上传文件时,当文件的大小大于8M时,上传不能不成功. 首先,我想到了nginx的client_m ...

  9. 对于Nginx+PHP实现大文件上传时候需要修改的参数

    post_max_size表示POST表单提交的最大大小upload_max_filesize 表示文件上传的最大大小. 通常post_max_size设置的值必须必upload_max_filesi ...

随机推荐

  1. 2019DX#2

    Solved Pro.ID Title Ratio(Accepted / Submitted)   1001 Another Chess Problem 8.33%(1/12)   1002 Beau ...

  2. POJ3321 - Apple Tree DFS序 + 线段树或树状数组

    Apple Tree:http://poj.org/problem?id=3321 题意: 告诉你一棵树,每棵树开始每个点上都有一个苹果,有两种操作,一种是计算以x为根的树上有几个苹果,一种是转换x这 ...

  3. c++ uconcontext.h实现协程

    目录 c++ uconcontext.h实现协程 什么是协程? ucontext.h库 库的使用示例 代码地址 c++ uconcontext.h实现协程 什么是协程? 协程是一种程序组件,是由子例程 ...

  4. Quartz.Net使用教程

    在项目的开发过程中,难免会遇见后需要后台处理的任务,例如定时发送邮件通知.后台处理耗时的数据处理等,这个时候你就需要Quartz.Net了. Quartz.Net是纯净的,它是一个.Net程序集,是非 ...

  5. 字符串的api (基础)

    一.基础 1.字符串.charAt(index) 根据下标获取字符串的某一个字符 应用: 判断字符串的首字母是否大写 任意给定的一串字母,统计字符串里面的大写字母和小写字母的个数 2.字符串.inde ...

  6. jQuery - 03. each、prevaAll、nextAll、获取属性、修改属性attr/val/text()、jq.height/width、offset()./position()./scrol Left/Top 、事件绑定bind、delegate、on、事件解绑、事件对象、多库共存

    each 方法 $ ( selector).each(function( index,element) {  } );   参数一表示当前元素在所有匹配元素中的索引号 参数二表示当前元素(DOM对象) ...

  7. Tomcat性能调优参数简介

    近期,我们的一个项目进入了试运营的阶段,在系统部署至阿里云之后,我们发现整个系统跑起来还是比较慢的,而且,由于代码的各种不规范,以及一期进度十分赶的原因,缺少文档和完整的测试,整个的上线过程一波三折. ...

  8. 【Offer】[4] 【二维数组中的查找】

    题目描述 思路分析 Java代码 代码链接 题目描述 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数 ...

  9. <xsl:apply-templates>和<xsl:call-template>的区别

    <xsl:apply-templates> 应用模板,故名思意,将定义好的模板应用到 XML 的节点上.  可以调用 XML 文档的节点,使 XSL 文档可以渲染 XML 元素内的数据,  ...

  10. eclipse wifi 连接手机

    参考:http://blog.csdn.net/onlyonecoder/article/details/9121397 首先打开手机的wifi设置,使其连接到网络.然后,需要在手机上对adb连接端口 ...