环境安装
在NuGet资源包管理器上下载资源包:
1 visual studio2022 打开NuGet资源包管理器:
2. 安装webAPI Client
3. 安装Multipart Reader
4. 安装Json.Net
c# 实现Post form-data文件上传
internal class HttpClientUtils
{
public static string PostData(string filePath, string filename)
{
string str = "";
Console.WriteLine(ConfigurationManager.AppSettings["ftpIP"]);
try
{
HttpClient client = new HttpClient();
var postContent = new MultipartFormDataContent(); // 提交表单内容
//postContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); // 表头格式
FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read); // 打开文件读取数据流
//postContent.Headers.ContentLength = fileStream.Length; // 文件大小
postContent.Add(new StreamContent(fileStream), "file", filename);
HttpResponseMessage response = client.PostAsync(ConfigurationManager.AppSettings["ftpIP"], postContent).Result; // 提交表单信息
str = response.Content.ReadAsStringAsync().Result;
//fileStream.Close();
}
catch (Exception ex)
{
throw ex;
}
return str;
}
}