作用原理:把图片文件上传至项目里的某个文件夹下,文件名添加至数据库,展示图片的时候,该文件夹的路径+文件名
在窗体上添加上传图片按钮:
// 需要添加的引用
using System.IO; // FileInfo
using System.Windows.Forms; // OpenFileDialog
// 用到的组件: Button、PictureBox、openFileDialog(打开文件管理器)
public static string img;//声明一个全局变量存储上传之后的文件名
//获取项目根目录
private static string GetApplicationPath()
{
string path = Application.StartupPath;
string folderName = String.Empty;
while (folderName.ToLower() != "bin")
{
path = path.Substring(0, path.LastIndexOf("\\"));
folderName = path.Substring(path.LastIndexOf("\\") + 1);
}
return path.Substring(0, path.LastIndexOf("\\") + 1);
}
//上传按钮事件
private void btnUpload_Click(object sender, EventArgs e)
{
//文件根目录
string path = GetApplicationPath();
DialogResult dr = openFileDialog1.ShowDialog();
if (dr == DialogResult.OK)
{
string file = openFileDialog1.FileName;
string filename = file.Substring(file.LastIndexOf("\\") + 1); //格式化处理,提取文件名
//MessageBox.Show(name);
pictureBox1.Image = Image.FromFile(file);
bool ret = File.Exists(@path + "\\Image\\" + filename);//判断文件是否存在,返回一个bool值
//MessageBox.Show(ret.ToString());
if (ret)
{
MessageBox.Show("该图片文件已存在,建议更换");
}
else
{
File.Copy(openFileDialog1.FileName, path + "\\Image\\" + filename);
}
string imgpath = GetApplicationPath() + "//Image//";
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //使图像拉伸或收缩,以适合PictureBox
pictureBox1.Image = Image.FromFile(imgpath + filename);
img = filename;
}
}