C#.NET前台:<asp:Image ID="imgFood" runat="server" /> <asp:FileUpload ID="fileUpLoadPic" runat="server" /> <asp:Button ID="Button1" runat="server" Text="上傳" onclick="btnPicUpload_Click"/> 后台.CS文件: protected void btnPicUpload_Click(object sender, EventArgs e) //上傳按鈕 { if (fileUpLoadPic.HasFile) //文件存在 { SaveFile(fileUpLoadPic.PostedFile);//保存上傳文件 } else { Response.Write("<script>alert('上傳文件不存在!')</script>"); } if (fileUpLoadPic.PostedFile.FileName == "") //文件名字 { Response.Write("<script>alert('你還沒有選擇圖片!')</script>"); } else { string filepath = fileUpLoadPic.PostedFile.FileName; string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//第一個\轉義字符 Session["filename"] = filename; string fileEx = filepath.Substring(filepath.LastIndexOf(".") + 1);//從.開始截至最后得到圖片格式.jpg。。。 string serverpath = Server.MapPath("\\images\\") + filename; if (fileEx == "jpg" || fileEx == "bmp" || fileEx == "gif") { imgFood.ImageUrl = "images/" + filename; Response.Write("<script>alert('上傳成功!')</script>"); return; } else { Response.Write("<script>alert('上傳的格式有問題!')</script>"); return; } } } public void SaveFile(HttpPostedFile file) { string savePath = "C:\\Users\\DJJ\\Desktop\\School_Canteen2\\Web\\images\\"; string fileName = fileUpLoadPic.FileName; string pathToCheck = savePath + fileName; string tempfilename = ""; if (System.IO.File.Exists(pathToCheck)) { int counter = 2; while (System.IO.File.Exists(pathToCheck)) { tempfilename = counter.ToString() + fileName; pathToCheck = savePath + tempfilename; counter++; } fileName = tempfilename; Response.Write("<script>alert('你上傳了兩個相同文件!')</script>"); } savePath += fileName; fileUpLoadPic.SaveAs(savePath); } 若前台要保存圖片路徑到數據庫:獲取路徑方式 (以string數據類型保存) string F_Pic = Convert.ToString(Session["filename"]);//this.fileUpLoadPic.FileName;//fileUpLoadPic.AppRelativeTemplateSourceDirectory;//圖片的數據庫中保存圖片路徑 string f_pic = F_Pic.Substring(0, F_Pic.LastIndexOf(".")); //得到去掉.jpg后的名字
選擇文件后,點擊上傳即可,上述代碼雖有提示上傳相同圖片的功能,但還是會上傳,若不想上傳要做具體處理。