How to upload files to a server using WinForms
In WinForms, you can upload files to a server by using the OpenFileDialog component to select the file you want to upload, and then using the WebClient component to upload the file to the server.
Firstly, you need to add the OpenFileDialog and WebClient components to the form.
Next, write the code for uploading the file in the button’s click event. It is shown below:
private void btnUpload_Click(object sender, EventArgs e)
{
// 使用OpenFileDialog选择要上传的文件
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string fileName = openFileDialog.FileName;
// 创建WebClient对象
WebClient webClient = new WebClient();
try
{
// 上传文件
webClient.UploadFile("http://example.com/upload", fileName);
MessageBox.Show("上传成功!");
}
catch (Exception ex)
{
MessageBox.Show("上传失败:" + ex.Message);
}
finally
{
// 释放资源
webClient.Dispose();
}
}
}
Replace http://example.com/upload in the above code with the actual server upload endpoint address.
Note: When using WebClient to upload files, make sure that the server has the correct interface to receive and save the uploaded file.
In addition, if you need to display the upload progress during the file uploading process, you can use the UploadProgressChanged event to achieve this.