FileUpload 服务器控件示例
简介
FileUpload 服务器控件示例
小结
自引入 Microsoft ASP.NET 版本 1.0 之日起,就存在生成 Web 应用程序的内置方法,这些方法能够将文件上载到宿主服务器。这是通过使用 File Field HTML 服务器控件实现的。我以前写过一篇关于如何在 ASP.NET 应用程序中有效使用该控件的 MSDN 文章。本文将再次介绍文件上载过程,但不是使用 File Field 控件,我将向您介绍如何有效使用 ASP.NET 2.0 提供的新 FileUpload 服务器控件。
FileUpload 服务器控件示例
在 ASP.NET 1.x 中使用 File Field 控件时,必须采取一些额外的步骤才能使一切有条不紊地正常运行。例如,您需要亲自将 enctype="multipart/form-data" 添加到页面的 <form> 元素中。ASP.NET 2.0 中提供的新 FileUpload 服务器控件使将文件上载到宿主服务器的过程尽可能的简单。
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
If FileUpload1.HasFile Then
Try
FileUpload1.SaveAs("C:\Uploads\" & _
FileUpload1.FileName)
Label1.Text = "File name: " & _
FileUpload1.PostedFile.FileName & "<br>" & _
"File Size: " & _
FileUpload1.PostedFile.ContentLength & " kb<br>" & _
"Content type: " & _
FileUpload1.PostedFile.ContentType
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
End Sub
</script>
<head runat="server">
<title>Upload Files</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ASP:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<ASP:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Upload File" /> <br />
<br />
<ASP:Label ID="Label1" runat="server"></ASP:Label></div>
</form>
</body>
</HTML>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs("C:\\Uploads\\" +
FileUpload1.FileName);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
</script>
<head runat="server">
<title>Upload Files</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ASP:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<ASP:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Upload File" /> <br />
<br />
<ASP:Label ID="Label1" runat="server"></ASP:Label></div>
</form>
</body>
</HTML>
<head><title>
Upload Files
</title></head>
<body>
<form name="form1" method="post" action="MyFileUpload.ASPx"
id="form1" enctype="multipart/form-data">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNDcxNTg5NDg3D2QWAgIEDxYCHgdlbmN0eXBlBRNtdWx0aXBhcnQvZm9yb
S1kYXRhZGQUQEUFMY1+/fp1mnrkbqmVNQIzFA==" />
</div>
<input type="file" name="FileUpload1" id="FileUpload1" /><br />
<br />
<input type="submit" name="Button1" value="Upload File"
id="Button1" /> <br />
<br />
<span id="Label1"></span>
</div>
<div>
value="/wEWAgLB+7jIAwKM54rGBv2Iz6LxVY7jWec0gZMxnuaK2ufq" />
</div></form>
</body>
</HTML>