winform调用webapi 实现文件上传
时间: 2023-09-08 17:13:39 浏览: 81
您可以使用HttpClient类来调用Web API并实现文件上传。以下是一个简单的WinForms代码示例:
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Windows.Forms;
namespace WinFormsFileUpload
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
// 添加文件
var fileContent = new ByteArrayContent(File.ReadAllBytes(textBox1.Text));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
content.Add(fileContent, "file", Path.GetFileName(textBox1.Text));
// 添加其他参数
var values = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2", "value2" }
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
// 发送请求
var response = await client.PostAsync("http://example.com/api/upload", content);
if (response.IsSuccessStatusCode)
{
MessageBox.Show("上传成功!");
}
else
{
MessageBox.Show("上传失败!");
}
}
}
}
}
}
```
在上面的示例中,我们使用MultipartFormDataContent类来创建请求正文,然后使用HttpClient类发送请求。请注意,我们还添加了其他参数(param1和param2)作为请求正文的一部分。如果请求成功,我们将显示一个消息框,否则将显示另一个消息框。