C# HttpPost 【ContentType:multipart/form-data】表单提交 file 类型数据方法 2
参考来源:https://blog.csdn.net/qq_39788123/article/details/128495546
try
{
Dictionary<string, string> headerDict = new Dictionary<string, string>();
NameValueCollection par = new NameValueCollection();
//par.Add("dataSource", "数据源"); //数据源
dynamic fileInfo = new ExpandoObject();
fileInfo.fileName = "C:/Users/admin/Desktop/ico/A001.png"; //文件名
byte[] fileByte = File.ReadAllBytes("C:/Users/admin/Desktop/ico/A001.png");
fileInfo.fileByte = fileByte; //文件字节
fileInfo.file = "file"; //字段名
//请求
string result = PostMultipartFormDataAsync("https://*******.co.th/**/getFileUrl", headerDict, par, fileInfo);
}
catch (System.Exception ex)
{
Console.Write("SendThaiFormData Error:" + ex.Message);
}
/// <summary>
/// 使用multipart/form-data方式上传文件及其他数据
/// </summary>
/// <param name="requestUrl">请求接口地址</param>
/// <param name="headers">自定义header</param>
/// <param name="nameValueCollection">键值对参数</param>
/// <param name="fileInfo">文件信息</param>
/// <returns></returns>
public static string PostMultipartFormDataAsync(string requestUrl, Dictionary<string, string> headers, NameValueCollection nameValueCollection, dynamic fileInfo)
{
var data = "";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
using (var httpClient = new HttpClient())
{
try
{
//header参数
foreach (var item in headers)
{
httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
using (var reduceAttach = new MultipartFormDataContent())
{
#region 键值对参数
string[] allKeys = nameValueCollection.AllKeys;
foreach (string key in allKeys)
{
var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key]));
dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = key
};
reduceAttach.Add(dataContent);
}
#endregion
#region 文件参数
if (fileInfo != null)
{
Stream fileStream = new MemoryStream(fileInfo.fileByte); //转成stream流
var streamContent = new StreamContent(fileStream);
var Content = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);//创建文件的content
reduceAttach.Add(Content, fileInfo.file, fileInfo.fileName);
streamContent.Dispose();
}
#endregion
//请求
var response = httpClient.PostAsync(requestUrl, reduceAttach).Result;
data = response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception ex)
{
throw ex;
}
}
return data;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?