对课本上的代码进行了一点的优化 1.获取文件的名称和文件的后缀名
引用了System.IO,
用Path.GetFileNamehe()取得文件名和Path.GetExtension获取文件的后缀
2.对上传的文件进行了重命名
采用Guid全局唯一标识进行命名
Guid.NewGuid().ToString()
3.根据日期创建文件夹,先判断文件夹是否存在,不存在就创建一个
创建文件夹:Directory.CreateDirectory(dir)
string dir = “/Images/“ + DateTime.Now.Year + “-“ + DateTime.Now.Month + “-“ + DateTime.Now.Day + “/“;
判断文件夹是否存在
Directory.Exists(Server.MapPath(dir))

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| protected void Button1_Click(object sender, EventArgs e) { if (Fileupload1.HasFile) { //获取文件名 string filePath = Path.GetFileName(Fileupload1.FileName);
//获取文件后缀 string fileExt = Path.GetExtension(filePath);
//检查文件类型 是否为图片文件 if (!IsImg(fileExt)) return;
//创建文件夹,以年月日创建 string dir = "/Images/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "/";
//判断文件夹是否存在,不存在就创建 if(!Directory.Exists(Server.MapPath(dir))) Directory.CreateDirectory(Server.MapPath(dir));
//给图片进行重命名,Guid唯一标识 string newFileName = Guid.NewGuid().ToString();
//文件的相对路径 string fileDir = dir + newFileName + fileExt;
//上传到服务器 Fileupload1.SaveAs(Server.MapPath(fileDir));
//显示图片 Image1.ImageUrl = fileDir; } else { Response.Write("<Script>alert('请选择上传图片!')</Script>"); } }
// 判断文件后缀名 private bool IsImg(string fileExt) { string[] ext = new string[] { ".jpg", ".png", ".gif", ".bmp", ".jpeg" }; for (int i = 0; i < ext.Length; i++) { if (fileExt.Equals(ext[i])) return true; } return false; }
|