c#文件上传

c#文件拥有自己的文件上传控件FileUpload。

使用FIieUpload控件上传文件:

前台代码:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
 protected void Button1_Click(object sender, EventArgs e)
    {
        bool filesValid = false;
        if (this.FileUpload1.HasFile)
        {
            //获取上传文件的后缀
            String fileExtension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();
            String[] restrictExtension = {".gif", ".jpg", ".bmp", ".png"};
            //判断文件类型是否符合要求
            for (int i = 0; i < restrictExtension.Length; i++)
            {
                if (fileExtension == restrictExtension[i])
                    filesValid = true;
            }
            //如果文件类型符合要求,调用SaveAs方法实现上传,并显示相关信息
            if (filesValid == true)
            {
                try
                {
                    this.Image1.ImageUrl = "~/images" + FileUpload1.FileName;
                    this.FileUpload1.SaveAs(Server.MapPath("~/images/") + FileUpload1.FileName);
                    this.Label1.Text = "文件上传成功";
                    this.Label1.Text += "<br/>";
                    this.Label1.Text += "<li>" + "原文件路径:" + this.FileUpload1.PostedFile.FileName;
                    this.Label1.Text += "<br/>";
                    this.Label1.Text += "<li>" + "文件大小:" + this.FileUpload1.PostedFile.ContentLength + "字节";
                    this.Label1.Text += "<br/>";
                    this.Label1.Text += "<li>" + "文件类型:" + this.FileUpload1.PostedFile.ContentType;
                }
                catch
                {
                    this.Label1.Text = "文件上传不成功!";
                }
            }
            else
            {
                this.Label1.Text = "文件类型不正确!";
            }

        }
        
    }
原文地址:https://www.cnblogs.com/sjyzz/p/7650542.html