代码改变世界

【Asp.Net从零开始】:上传文件(FileUpload)

2012-08-16 16:44  ATP_  阅读(954)  评论(0编辑  收藏  举报
public partial class FileUpload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btn_Save_onclick(object sender, EventArgs e)
    {
        Boolean fileOK = false;
        String path = Server.MapPath("~/Uploads/");
        if (fu.HasFile)
        {
            String fileExtension =
                System.IO.Path.GetExtension(fu.FileName).ToLower();
            String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension == allowedExtensions[i])
                {
                    fileOK = true;
                }
            }
        }

        if (fileOK)
        {
            try
            {
                fu.PostedFile.SaveAs(path + fu.FileName);
            }
            catch (Exception ex)
            {
               
            }
        }
        else
        {
           
        }
        
    }
}

  

<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="fu" runat="Server" MaxRequestLength="" BackColor="#6699FF" Height="42px" Width="257px" />
        <br />
        <asp:Button Text="存储" ID="btn_Save" runat="server" OnClick="btn_Save_onclick" 
            style="margin-left: 153px" />
    </div>
    </form>
</body>