WinForms File Upload with WebAPI
To upload a file in a WinForm application using WebAPI, you can utilize the HttpClient class to send HTTP requests. Here is a simple example code to demonstrate how to achieve this goal:
Firstly, you need to add a button and a file selection dialog in the WinForm application to select the file to upload.
Then, you can write the following code in the Click event of the button to call the WebAPI to upload a file.
private async void btnUpload_Click(object sender, EventArgs e)
{
using (HttpClient client = new HttpClient())
{
// 设置WebAPI的URL
string apiUrl = "http://example.com/api/uploadfile";
// 选择要上传的文件
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
// 读取文件内容
byte[] fileContent = File.ReadAllBytes(filePath);
// 创建MultipartFormDataContent对象
MultipartFormDataContent content = new MultipartFormDataContent();
ByteArrayContent fileContentData = new ByteArrayContent(fileContent);
content.Add(fileContentData, "file", Path.GetFileName(filePath));
// 发送HTTP请求
HttpResponseMessage response = await client.PostAsync(apiUrl, content);
if (response.IsSuccessStatusCode)
{
MessageBox.Show("文件上传成功!");
}
else
{
MessageBox.Show("文件上传失败");
}
}
}
}
In the code above, we are utilizing the HttpClient class to send a POST request, sending the file content as MultipartFormDataContent to a specified URL in a WebAPI. If the upload is successful, a success message box will be displayed, otherwise a failure message box will be shown.
Please ensure that the URL for the WebAPI is correctly configured before calling it, and make sure that the file selected in the file selection dialog actually exists.