前台代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadPic.aspx.cs" Inherits="UploadPicDemo.UploadPic" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>ASP.NET上传图片</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="imagePic" runat="server" />
        <br />
        <asp:FileUpload ID="fileUpload" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="上传" OnClick="btnUpload_Click" />
        <br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>

后台代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
        //上传按钮单击事件
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (fileUpload.HasFile)
            {
                //获取上传的文件名
                string fileName = fileUpload.FileName;
                //获取上传文件的文件后缀名
                string fileFix = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
                if (fileFix != "png" && fileFix != "jpg" && fileFix != "jpeg" && fileFix != "gif")
                {
                    this.lblMessage.Text = "上传的文件不是图片类型文件";
                }
                else
                {
                    fileUpload.SaveAs(Server.MapPath(".") + "//UploadPic//" + fileName);
                    this.imagePic.ImageUrl = "~/UploadPic/" + fileName;
                    this.lblMessage.Text = "图片上传成功!";
                }
            }
        }

这是一篇过去很久的文章,其中的信息可能已经有所发展或是发生改变。