ASP.NET 上传图片

2016-11-22
1分钟阅读时长

前台代码:

<%@ 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>

后台代码:

        //上传按钮单击事件
        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 = "图片上传成功!";
                }
            }
        }

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

本文作者:她和她的猫
本文地址https://her-cat.com/posts/2016/11/22/asp-net-upload-image/
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!