2019/10/27, .Net c#代码片段

摘要:使用HttpWebRequest向Api接口发送文件,multipart-form数据格式,POST方式

参考地址

/// <summary>
/// HttpWebRequest发送文件
/// </summary>
/// <param name="url">url</param>
/// <param name="filePath">文件路径</param>
/// <param name="paramName">文件参数名</param>
/// <param name="contentType">contentType</param>
/// <param name="nameValueCollection">其余要附带的参数键值对</param>
public static void HttpUploadFile(string url, string filePath, string paramName, string contentType, NameValueCollection nameValueCollection)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
Stream requestStream = request.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nameValueCollection.Keys)
{
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
requestStream.Write(formitembytes, 0, formitembytes.Length);
}
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", paramName, filePath, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
WebResponse webResponse = null;
try
{
webResponse = request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string result = streamReader.ReadToEnd();
}
catch (Exception ex)
{
if (webResponse != null)
{
webResponse.Close();
webResponse = null;
}
}
finally
{
request = null;
}
}

使用

NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "1000");
nvc.Add("name", "user1");
HttpUploadFile("http://your.server.com/upload",@"C:\test\test.jpg", "file", "image/jpeg", nvc);

使用HttpWebRequest POST上传文件的更多相关文章

  1. HttpWebRequest post上传文件

    public static string HttpUploadFile(string url, string path) { // 设置参数 HttpWebRequest request = WebR ...

  2. C# 使用HttpWebRequest通过PHP接口 上传文件

    1:上传文件实例 public void UploadXMLLog(string xmlpath)         {             NameValueCollection nvc = ne ...

  3. HttpWebRequest上传文件(Excel等)

    //上传代码/// <summary> /// 文件上传 /// </summary> /// <param name="strAddress"> ...

  4. ASP.NET上传文件到远程服务器(HttpWebRequest)

    /// <summary> /// 文件上传至远程服务器 /// </summary> /// <param name="url">远程服务地址 ...

  5. C#使用HttpWebRequest和HttpWebResponse上传文件示例

    C#使用HttpWebRequest和HttpWebResponse上传文件示例 1.HttpHelper类: 复制内容到剪贴板程序代码 using System;using System.Colle ...

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

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

  7. 关于HttpWebRequest上传文件

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

  8. HTTPWebrequest上传文件--Upload files with HTTPWebrequest (multipart/form-data)

    使用HTTPWebrequest上传文件遇到问题,可以参考Upload files with HTTPWebrequest (multipart/form-data)来解决 https://stack ...

  9. ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合

    一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...

随机推荐

  1. QElapsedTimer定时器记录程序执行时间

    QElapedTimer类提供了一种快速计算运行时间的方法,从Qt4.7引入. QElapsedTimer类通常用于快速计算两个事件之间经过了多少时间.它的API与QTime相似,因此可以将正在使用的 ...

  2. Android端项目测试

    目录 一.概述 二.使用工具 三.测试 1.测试主要的两大功能 进入主界面,测试排行榜查看功能是否能运行 测试83端口打卡能否运行 修改个人信息已经注册功能 2.测试参数是否正确 3.测试刷新能否使用 ...

  3. python字典中显示中文

    #coding=utf-8import jsondict={'title':"这是中文"}print json.dumps(dict,ensure_ascii=False,enco ...

  4. Anaconda3(5-2)程序编辑器 win10下PyCharm安装及配置Pytorch流程

    由于破解和付费问题,不推荐.优先用自带的spyder Win10 下PyCharm安装流程:(1)官网:https://www.jetbrains.com/pycharm/download/#sect ...

  5. IIS 登录失败 该登陆名来自不受信任的域,不能与windows身份认证一起使用

    原文:https://blog.csdn.net/hhw199112/article/details/80234462 错误: 登录失败 该登陆名来自不受信任的域,不能与windows身份认证一起使用 ...

  6. ESA2GJK1DH1K升级篇: STM32远程乒乓升级,基于GPRS模块AT指令TCP透传方式,定时访问升级(含有数据校验)

    实现功能概要 单片机定时使用http访问云端的程序版本,如果版本不一致, 然后通过http下载最新的升级文件,实现远程升级STM32程序. 兼容Air202 ,SIM800 测试准备工作(默认访问我的 ...

  7. 洛谷 P2615 神奇的幻方

    传送门 I'm here! 思路 这个题,我们可以直接去模拟,因为范围很小,且\(N\)都是奇数 直接构造一个矩阵,初始值都为\(0\),然后\(while\)循环,根据题目给出的\(4\)个条件进行 ...

  8. Python中的next()\iter()函数详解

    什么是可迭代的对象(Iterable,即可以用for循环的对象)和迭代器(Iterator) Iterable: 一类是:list.tuple.dict.set.str 二类是:generator(都 ...

  9. 设置 npm 源为淘宝镜像

    淘宝 npm 网址 https://npm.taobao.org/ 修改 npm config set registry http://registry.npm.taobao.org/ 还原 npm ...

  10. The import junit cannot be resolved解决问题

    第一次安装Junit,配置环境之后发现添加语句import junit.framework.TestCase; 编译错误 解决:项目右键Properties->Java Build Path-& ...