FileUpload控件的使用

2012/11/28 15:44
阅读数 219
 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网络安全小组



原文链接: http://blog.csdn.net/mypc2010/article/details/7046291
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部