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. Java多线程上下文切换

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10843676.html 一:什么是上下文切换 CPU处理任务时不是一直只处理一个,而是通过给每个线程分配CP ...

  2. MySQL服务的构成(二)

    一.什么是实例 这里的实例不是类产生的实例对象,而是Linux系统下的一种机制 1.MySQL的后台进程+线程+预分配的内存结构. 2.MySQL在启动的过程中会启动后台守护进程,并生成工作线程,预分 ...

  3. Jupyter Notebook 更换主题(背景、字体)

    通过命令行窗口或 Anaconda Prompt 窗口 1.安装 Jupyter 主题 pip install jupyterthemes 2.更新 Jupyter 主题 (可选) pip insta ...

  4. 201871010131-张兴盼《面向对象程序设计(java)》第二周学习总结

    项目 内容 <面向对象程序设计(java)> https://home.cnblogs.com/u/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.c ...

  5. CentOS7 最小安装 vmware 创建虚拟机 nmcli ip systemctl

    镜像网站 一些开源软件的国内镜像源 站点版 (一).企业站 1.搜狐:http://mirrors.sohu.com/ 2.网易:http://mirrors.163.com/ 3.阿里云:http: ...

  6. .Net反射-TypeDescriptor

    .Net中提供了两种方式访问类型的元数据:System.Reflection命名空间中提供的反射API和TypeDescriptor类.反射适用于所有类型的常规机制,它为类型返回的信息是不可扩展的,因 ...

  7. web前端图片模糊到清晰的实现过程

    在网页图片显示的时候,会发现许多网站采用了先模糊,然后在慢慢清晰的过程,这样的加载用户体验是比较好的,那么如何实现? 默认加载2张图片,一张缩略图,一张原图,当打开网页的时候默认只显示缩略图,然后我们 ...

  8. 【Gamma】项目展示

    团队成员介绍 大娃 :后端开发人员,主要工作为后端开发,文档撰写. 大娃的个人博客 二娃 PM,主要工作为项目进度把控,例会博客撰写. 二娃的个人博客 三娃* PM,主要工作为项目进度把控,用户需求分 ...

  9. 终于有人把elasticsearch原理讲通了

    转自 小史是一个非科班的程序员,虽然学的是电子专业,但是通过自己的努力成功通过了面试,现在要开始迎接新生活了. 随着央视诗词大会的热播,小史开始对诗词感兴趣,最喜欢的就是飞花令的环节. 但是由于小史很 ...

  10. C运算符优先级和结合性

    C中运算符优先级和结合性一览表: 在上表中能总结出一下规律: (1)结合方向只有三个是从右往左,其余都是从左往右: (2)逗号运算符的优先级最低: (3)对于优先级,有一个普遍规律:算术运算符 > ...