FileUpload控件的使用

本文详细介绍了ASP.NET中FileUpload控件的使用方法,包括如何限制上传文件类型及如何将文件保存到服务器指定目录。通过具体示例代码展示了完整的上传流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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网络安全小组


转载于:https://www.cnblogs.com/secbook/archive/2011/12/06/2654919.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值