名 称 类型 读 写 说 明
FileContent Stream × 返回一个指向上传文件的流对象
FileName string × 返回要上传文件的名称,不包含路径信息
HasFile Boolean × 如果是true,则表示该控件有文件要上传
PostedFile HttpPostedFile × 返回已经上传文件的引用。表5-9列出了它所公开的只读属性
名 称 类 型 读 写 说 明
ContentLength integer × 返回上传文件的按字节表示的文件大小
ContentType string × 返回上传文件的MIME内容类型
FileName string × 返回文件在客户端的完全限定名
InputStream Stream × 返回一个指向上传文件的流对象
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “”>
<html xmlns=”” >
<head runat=”server”>
<title>FileUpload Control</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<h1>FileUpload Control</h1>
<asp:FileUpload ID=”FileUpload1” runat=”server” />
<br />
<asp:Button ID=”btnSave” runat=”server” Text=”Save” OnClick=”btnSave_Click” />
<asp:Button ID=”btnDisplay” runat=”server” Text=”Display” OnClick=”btnDisplay_Click” />
<br />
<br />
<asp:Label ID=”lblMessage” runat=”server” />
<asp:Label ID=”lblDisplay” runat=”server” />
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
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;
using System.IO; // 使用Stream必需
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{}
protected void btnSave_Click(object sender, EventArgs e)
{
string str = “”;
if (FileUpload1.HasFile)
{
try
{
str += “Uploading file: “ + FileUpload1.FileName;
// 保存文件
FileUpload1.SaveAs(“c:\websites\uploads\” + FileUpload1.FileName);
// 显示文件信息
str += “<br/>Saved As: “ + FileUpload1.PostedFile.FileName;
str += “<br/>File Type: “ + FileUpload1.PostedFile.ContentType;
str += “<br/>File Length (bytes): “ + FileUpload1.PostedFile.ContentLength;
str += “<br/>PostedFile File Name: “ + FileUpload1.PostedFile.FileName;
}
catch (Exception ex)
{
str += “<br/><b>Error</b><br/>Unable to save
c:\websites\uploads\” + FileUpload1.FileName +“<br/>” + ex.Message;
}
}
else
{
str = “No file uploaded.”;
}
lblMessage.Text = str;
lblDisplay.Text = “”;
}
protected void btnDisplay_Click(object sender, EventArgs e)
{
string str = “<u>File: “ + FileUpload1.FileName + “</u><br/>”;
if (FileUpload1.HasFile)
{
try
{
Stream stream = FileUpload1.FileContent;
StreamReader reader = new StreamReader(stream);
string strLine = “”;
do
{
strLine = reader.ReadLine( );
str += strLine;
} while (strLine != null);
}
catch (Exception ex)
{
str += “<br/><b>Error</b><br/>Unable to display “ + FileUpload1.FileName +
“<br/>” + ex.Message;
}
}
else
{
str = “No file uploaded.”;
}
lblDisplay.Text = str;
lblMessage.Text = “”;
}
}