C#.net实现图片上传功能

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后的名字

选择文件后,点击上传即可,上述代码虽有提示上传相同图片的功能,但还是会上传,若不想上传要做具体处理。
posted @ 2016-08-14 12:31  小-波  阅读(18050)  评论(2编辑  收藏  举报