.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;

}

相关推荐
大风起兮云飞扬丶3 小时前
Java——线程池
java·开发语言
我命由我123453 小时前
Python 开发 - Python 虚拟环境
运维·开发语言·后端·python·http·https·java-ee
c#上位机3 小时前
C#上位机项目实战——exe项目调试更改dll中源代码
开发语言·c#
basketball6163 小时前
C++ 中字符串与常见类型的转换总结
开发语言·c++
梦影_3 小时前
MySQL进阶教程(一)—— 储存过程与触发器(上)
开发语言·数据库·后端·sql·mysql·中间件
云和数据.ChenGuang3 小时前
LLM大模型对接本地Ollama部署模型
开发语言·人工智能·python·langchain
等我调个Bug4 小时前
C++智能指针通俗讲解
开发语言·c++
黑化旺仔4 小时前
【OC】Runtime:类元数据、加载初始化与消息派发
开发语言·macos·ios·objective-c
Felven4 小时前
C. Removing Smallest Multiples
c语言·开发语言
云和数据.ChenGuang4 小时前
光哥说Python 循环导入(Circular Import)深度解析:成因、排查与解决方案
开发语言·前端·人工智能·python·langchain