C#. NET front desk: <asp:image id= "Imgfood" runat= "server"/> <asp:fileupload id="Fileuploadpic" runat="Server"/> <asp:button id="Button1" runat="Server" text="Upload" onclick="Btnpicupload_click"/> Backstage. CS File:ProtectedvoidBtnpicupload_click(Object sender, EventArgs e)Upload button {if (fileuploadpic.hasfile)File exists {SaveFile (fileuploadpic.postedfile);Save upload file}else {Response.Write ("<script>alert (' upload file does not exist! ') </script> "); }if (FileUpLoadPic.PostedFile.FileName = ="")File name {Response.Write ("<script>alert (' You haven't selected the picture yet! ') </script> "); }else {string filepath = FileUpLoadPic.PostedFile.FileName;string filename = filepath. Substring (filepath. LastIndexOf ("\\") +1);First \ Escape character session["filename"] = filename;String Fileex = FilePath. Substring (filepath. LastIndexOf (".") +1);From. Start up to the end to get the picture format. jpg ...String Serverpath = Server.MapPath ("\\images\\") + filename;if (Fileex = ="JPG" | | Fileex = ="BMP" | | Fileex = ="GIF") {Imgfood.imageurl ="images/" + filename; Response.Write ("<script>alert (' upload success! ') </script> ");Return }else {Response.Write ("<script>alert (' uploading the format has a problem! ') </script> ");Return } } }PublicvoidSaveFile(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 (' you uploaded two identical files! ') </script> "); } Savepath + = FileName; Fileuploadpic.saveas (Savepath); If the foreground is going to save the picture path to the database: Gets the path way (saved as a string data type) string f_pic = convert.tostring (session["filename"]); this.fileuploadpic.filename;//fileuploadpic.apprelativetemplatesourcedirectory;//picture in the database save picture path string f_ pic = f_pic.substring (0, F_pic.lastindexof (".")); //get rid of. jpg name
选择文件后,点击上传即可,上述代码虽有提示上传相同图片的功能,但还是会上传,若不想上传要做具体处理。
C#.net implementation of image upload function