C# winform POST 上传form表单
写一个上传demo
URL:
http://117.72.17.59:39020/cyry/healthcheck/hisUploadTest
Header:
参数名称
OrgCode
Body:
Form表单格式:
pdf:PDF附件 file类型
picture:照片附件 file类型
data:文本 string 类型
C# winform POST 上传form表单
写一个上传demo
URL:
http://117.72.17.59:39020/cyry/healthcheck/hisUploadTest
Header:
参数名称
OrgCode
Body:
Form表单格式:
pdf:PDF附件 file类型
picture:照片附件 file类型
data:文本 string 类型
引自免费微信小程序:皆我百晓生
在C# Winform中,要实现一个POST上传表单数据(包括PDF附件和照片附件)的demo,你可以使用HttpClient类来发送请求。以下是一个完整的C#代码示例:
using System;
using System.Net.Http;
using System.IO;
using System.Net.Http.Headers;
using System.Threading.Tasks;
public class FormUploadDemo
{
public async Task<HttpResponseMessage> UploadFormData(string orgCode, string pdfFilePath, string pictureFilePath, string data)
{
var httpClient = new HttpClient();
// 设置Header
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_token_here"); // 如果需要身份验证,请替换为实际token
httpClient.DefaultRequestHeaders.Add("OrgCode", orgCode);
MultipartFormDataContent form = new MultipartFormDataContent();
// 添加PDF附件
byte[] pdfFileBytes = File.ReadAllBytes(pdfFilePath);
StreamContent pdfContent = new StreamContent(new MemoryStream(pdfFileBytes));
pdfContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/pdf");
form.Add(pdfContent, "pdf", Path.GetFileName(pdfFilePath));
// 添加照片附件
byte[] pictureFileBytes = File.ReadAllBytes(pictureFilePath);
StreamContent pictureContent = new StreamContent(new MemoryStream(pictureFileBytes));
pictureContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); // 假设是PNG格式图片
form.Add(pictureContent, "picture", Path.GetFileName(pictureFilePath));
// 添加文本数据
StringContent dataContent = new StringContent(data);
form.Add(dataContent, "data");
// 发送POST请求
HttpResponseMessage response = await httpClient.PostAsync("http://117.72.17.59:39020/cyry/healthcheck/hisUploadTest", form);
return response;
}
public async Task Run()
{
string orgCode = "47";
string pdfFilePath = @"C:\path\to\your\file\TestPDF.pdf";
string pictureFilePath = @"C:\path\to\your\file\照片测试.png";
string data = "QEtXXyUnHWbZWKuG9KFFLS4gP/NLOPmDJ/642neRLYkjn5vwSOkTb95+GMb2";
HttpResponseMessage response = await UploadFormData(orgCode, pdfFilePath, pictureFilePath, data);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"上传成功, 返回结果: {responseBody}");
}
else
{
Console.WriteLine($"上传失败, 状态码: {response.StatusCode}");
}
}
}
// 在你的Winform程序主方法或按钮事件处理程序中调用Run方法
public static void Main(string[] args)
{
FormUploadDemo demo = new FormUploadDemo();
demo.Run().Wait();
}
请注意替换上述代码中的your_token_here
为实际的认证令牌(如果接口需要的话),以及正确的文件路径pdfFilePath
和pictureFilePath
。
此代码片段展示了如何创建一个MultipartFormDataContent对象,并将PDF、照片附件以及文本数据添加到请求体中。然后通过HttpClient实例的PostAsync方法向指定URL发送POST请求。