1、拖拽上传图片
1.1、后台代码中修改窗体属性,添加 AllowDrop = true

1.2、给窗体添加拖拽事件,在事件列表找到拖拽 双击即可:

在 DragDrop 生成的方法中添加代码如下:
private void Form1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
}
在 DragEnter 方法中添加代码如下:
private void Form1_DragEnter(object sender, DragEventArgs e)
{
//判断
string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];
string file = files[0];
if (!file.ToLower().EndsWith(".png") && !file.ToLower().EndsWith(".jpg"))
{
MessageBox.Show("需要图片文件!");
return;
}
//PictureBox控件显示图片
Image.Load(file);
}
2、点击按钮上传图片
2.1、官方文档地址:https://msdn.microsoft.com/zh-cn/library/system.windows.controls.openfiledialog.filter(v=VS.95).aspx
2.2、在窗体中添加控件 OpenFileDialog ,提供了提示用户打开文件的功能。按钮添加代码如下:
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//PictureBox控件显示图片
Image.Load(openFileDialog.FileName);
}
}
2.3、上传图片并保存
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//PictureBox控件显示图片
Image.Load(openFileDialog.FileName);
//获取用户选择文件的后缀名
string extension = Path.GetExtension(openFileDialog.FileName);
//声明允许的后缀名
string[] str = new string[] { ".gif", ".jpge", ".jpg", ".png" };
if (!str.Contains(extension))
{
MessageBox.Show("仅能上传gif,jpge,jpg格式的图片!");
}
else
{
//获取用户选择的文件,并判断文件大小不能超过20K,fileInfo.Length是以字节为单位的
FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
if (fileInfo.Length > 20480)
{
MessageBox.Show("上传的图片不能大于20K");
}
else
{
//绝对路径
string image = openFileDialog.FileName;
// 是指XXX.jpg
string picpath = openFileDialog.SafeFileName;
File.Copy(openFileDialog.FileName, Application.StartupPath + "\\Image\\" + picpath);
}
}
}
}
来源:https://www.cnblogs.com/miskis/p/7607024.html