.net4.0 调用API(form-data)上传文件及传参

/// <summary>

///

/// </summary>

/// <param name="url">API URL</param>

/// <param name="token">API token</param>

/// <param name="parameters">API参数(除文件类型外)</param>

/// <param name="fileContent">文件参数(二进制文件流)</param>

/// <param name="fileName">文件名</param>

/// <returns></returns>

public string Post_formdata(string url, string token, Dictionary<string, string> parameters, byte[] fileContent, string fileName)

{

string result = "";

string strBoundary = "--" + DateTime.Now.Ticks.ToString("x");//程序生成

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.Method = "POST";

if (!string.IsNullOrEmpty(token))

{

WebHeaderCollection coll = new WebHeaderCollection();

coll.Add("token", token);

request.Headers = coll;

}

request.ContentType = "multipart/form-data;charset=UTF-8; boundary=" + strBoundary;

// 设置请求参数

StringBuilder sb = new StringBuilder();

foreach (KeyValuePair<string, string> kvp in parameters)

{

sb.AppendFormat("--" + strBoundary + "\r\n");

sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n", kvp.Key);

sb.AppendFormat("\r\n{0}\r\n", kvp.Value);

}

// 上传文件

sb.AppendFormat("--" + strBoundary + "\r\n");

sb.AppendFormat("Content-Disposition: form-data; name=\"uploadFile\"; filename=\"{0}\"\r\n", fileName); //uploadFile为参数名

//sb.AppendFormat("Content-Type: image/png\r\n");

sb.AppendFormat("Content-Type: octet-stream\r\n");

sb.AppendFormat("\r\n");

byte[] paramBytes= Encoding.UTF8.GetBytes(sb.ToString());

var footerBytes = Encoding.UTF8.GetBytes("\r\n--" + strBoundary + "--\r\n");

byte[] fileBytes = fileContent;

request.ContentLength += fileBytes.Length + paramBytes.Length + footerBytes.Length + 1;

using (Stream requestStream = request.GetRequestStream())

{

requestStream.Write(paramBytes, 0, paramBytes.Length);

requestStream.Write(fileBytes, 0, fileBytes.Length);

requestStream.Write(footerBytes, 0, footerBytes.Length);

}

HttpWebResponse resp;

try

{

resp = (HttpWebResponse)request.GetResponse();

}

catch (WebException ex)

{

resp = (HttpWebResponse)ex.Response;

}

Stream stream = resp.GetResponseStream();

//获取响应内容

using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))

{

result = reader.ReadToEnd();

}

resp.Close();

request.Abort();

return result;

}

相关推荐
yangzhi_emo2 分钟前
ES6笔记2
开发语言·前端·javascript
emplace_back1 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk1 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶1 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl1 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
收破烂的小熊猫~1 小时前
《Java修仙传:从凡胎到码帝》第四章:设计模式破万法
java·开发语言·设计模式
nananaij2 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
阿蒙Amon2 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
无小道2 小时前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++