在C# WinForms应用程序中上传图片,你可以使用OpenFileDialog
来让用户选择图片文件,然后使用WebRequest
或HttpClient
来发送图片到服务器。以下是一个简单的例子:
-
添加一个按钮到你的WinForms窗体上,用来触发上传操作。
-
实现按钮的点击事件处理程序来打开文件选择器,选择图片,并上传。
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void uploadButton_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "图片文件(*.jpg;*.jpeg;*.gif;*.bmp;*.png)|*.jpg;*.jpeg;*.gif;*.bmp;*.png";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// 获取选中的文件路径
string filePath = openFileDialog.FileName;
try
{
// 将图片转换为字节数组
Image image = Image.FromFile(filePath);
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, image.RawFormat);
byte[] imageBytes = ms.ToArray();
// 使用WebRequest上传图片
// 这里需要替换为你的服务器URL
string url = "http://yourserver.com/upload";
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.ContentLength = imageBytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(imageBytes, 0, imageBytes.Length);
}
using (WebResponse response = request.GetResponse())
{
// 处理服务器响应
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}