使用HttpWebRequest POST上传文件
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上传文件的更多相关文章
- HttpWebRequest post上传文件
public static string HttpUploadFile(string url, string path) { // 设置参数 HttpWebRequest request = WebR ...
- C# 使用HttpWebRequest通过PHP接口 上传文件
1:上传文件实例 public void UploadXMLLog(string xmlpath) { NameValueCollection nvc = ne ...
- HttpWebRequest上传文件(Excel等)
//上传代码/// <summary> /// 文件上传 /// </summary> /// <param name="strAddress"> ...
- ASP.NET上传文件到远程服务器(HttpWebRequest)
/// <summary> /// 文件上传至远程服务器 /// </summary> /// <param name="url">远程服务地址 ...
- C#使用HttpWebRequest和HttpWebResponse上传文件示例
C#使用HttpWebRequest和HttpWebResponse上传文件示例 1.HttpHelper类: 复制内容到剪贴板程序代码 using System;using System.Colle ...
- C#在WinForm下使用HttpWebRequest上传文件
转自:http://blog.csdn.net/shihuan10430049/article/details/3734398 这段时间因项目需要,要实现WinForm下的文件上传,个人觉得采用FTP ...
- 关于HttpWebRequest上传文件
我们web 操作离不开 http请求响应 HttpWebRequest上传文件也是一样的道理 下面码一些代码: private void UploadFile(string strRequestUri ...
- HTTPWebrequest上传文件--Upload files with HTTPWebrequest (multipart/form-data)
使用HTTPWebrequest上传文件遇到问题,可以参考Upload files with HTTPWebrequest (multipart/form-data)来解决 https://stack ...
- ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合
一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...
随机推荐
- Python:日常应用汇总
判断路径中是否包含中文 import re def IsContainChinese(path:str) -> bool : cnPatter=re.compile(u'[\u4e00-\u9f ...
- U-Boot的常用命令详解
U-Boot还提供了更加详细的命令帮助,通过help命令还可以查看每个命令的参数说明.由于开发过程的需要,有必要先把U-Boot命令的用法弄清楚.接下来,根据每一条命令的帮助信息,解释一下这些命令的功 ...
- DataOps Reading Notes
质量.效率.成本.安全,是运维工作核心四要素. AIOps 技术会涉及到数据收集方面的基础监控,服务监控和业务监控,甚至会涉及到与持续交付流水线的数据和状态整合(比如在软件发布的阶段会自动关闭某些监控 ...
- Codeforces Global Round 3 题解
这场比赛让我上橙了. 前三题都是大水题,不说了. 第四题有点难想,即使想到了也不能保证是对的.(所以说下面D的做法可能是错的) E的难度是 $2300$,但是感觉很简单啊???说好的歪果仁擅长构造的呢 ...
- React 积累
1. Fragment 标签 使用介绍:因React要求每个组件都需要一个大的外层包裹起来才可以,否则报错,如果你并不想组件外层由一个大大外层包裹,则可以使用Fragment 标签 代码示例: imp ...
- CDN惹的祸:记一次使用OSS设置跨域资源共享(CORS)不生效的问题
原文: https://www.lastupdate.net/4669.html 昨天H5组的开发反馈了一个问题,说浏览器收不到跨域的配置,提示:Failed to load https://nnmj ...
- klass-oop
(1)Klass Klass 简单来说就是 Java 类在 HotSpot 中的 C++ 对等体,主要用于描述对象实例的具体类型.一般 JVM 在加载 class 文件时,会在方法区创建 Klass ...
- Python UDP小程序
为了做UDP的测试,采用了nc和Python的服务器端. nc的安装和使用: yum install -y nc nc -vuz Python的UDP服务器端小程序: # -*- coding: UT ...
- ASP.NET之MVC 微信公众号授权给第三方平台的技术实现流程(获取第三方平台access_token)
“出于安全考虑,在第三方平台创建审核通过后,微信服务器每隔10分钟会向第三方的消息接收地址推送一次component_verify_ticket,用于获取第三方平台接口调用凭据”.这是文档中的原话,也 ...
- odoo13 searchpanel tree
<record id="view_department_filter" model="ir.ui.view"> <field name=&qu ...