首页 > 代码库 > 上传图片文件

上传图片文件

此处上传文件,使用FileUpload控件。

图片上传 :<asp:FileUpload ID="FileUpload1" runat="server" onchange="PreviewImg(this)" /> <asp:HiddenField ID="hildimage" runat="server" />

下面是代码:

    public void upload_Click()    {        try        {            if (FileUpload1.PostedFile.FileName == "")            {                  check.showMess(this, "图片不能为空!");            }            else            {                string fullname = FileUpload1.FileName.Replace(",", " ").Trim();                string typ2 = fullname.Substring(fullname.LastIndexOf(".") + 1).ToLower().ToString();                string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + typ2;                if (typ2 == "gif" || typ2 == "jpg" || typ2 == "bmp" || typ2 == "png")                {                    string img = hildimage.Value;                    if (img != "")                    {                        string imgpath = Server.MapPath("../" + img);                        File.Delete(imgpath);                    }                    FileUpload1.SaveAs(Server.MapPath("../upload/") + fn);           //将文件保存在根目录的UP文件夹下                      hildimage.Value = http://www.mamicode.com/"upload/" + fn;                }                else                {                    check.Show_ErrorMsg("文件类型不支持!");                    Response.End();                }            }        }        catch (Exception ex)        {            check.Show_ErrorMsg("上传发生错误!原因是:" + ex.ToString());            Response.End();        }    }