FileUpload控件的使用

 FileUpload控件,主要用来上传文件。关键的方法就是saveas(),即将本地文件“另存到"(上传)服务器的某个指定的目录.

 FileUpload.aspx内容:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUpLoad.aspx.cs" Inherits="FileUpLoad" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>上次文件</title>
</head>
<body>
    <form runat="server">
    <div>
        上传文件:<asp:FileUpload runat="server" Width="237px" />
        <asp:Button runat="server" Text="上传" Width="79px" />
        <asp:Label runat="server" Text="Label" Width="300px"></asp:Label><br />
        <br />
    </div>
    </form>
</body>
</html>
Uploadfile.aspx.cs内容:

 using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class FileUpLoad : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            Boolean fileOK = false;
            String path = Server.MapPath("~/Images/");  //设置服务器上传的路径,即文件上传的位置
            if (FileUpload1.HasFile)
            {
                String fileExtension =
                    System.IO.Path.GetExtension(FileUpload1.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
                {
                    FileUpload1.PostedFile.SaveAs(path
                        + FileUpload1.FileName);
                    Label1.Text = "文件上传成功!";
                }
                catch (Exception ex)
                {
                    Label1.Text = "文件不能上传.";
                }
            }
            else
            {
                Label1.Text = "不能接受这种文件类型。";
            }
        }
    }

}

 

来源于:www.hackbadboy.com  B.B.S.T 信息安全团队 BadBoy网络安全小组


posted @ 2011-12-06 15:19  MXi4oyu  阅读(201)  评论(0编辑  收藏  举报