前台:
<body>
<form id="Form1"runat="server">
<div>
<fieldset>
<legend>FileUpload控件典型应用</legend>
<br />
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="BtnUpload" runat="server" Text="上传"OnClick="BtnUpload_Click" />
<hr />
<asp:Label ID="LabMessage1" runat="server"ForeColor="red" /><br/>
<asp:Label ID="LabMessage2" runat="server"/>
</fieldset>
</div>
</form>
</body>
后台:
protectedvoid BtnUpload_Click(object sender, EventArgs e)
{
bool fileOK = false;
//Server.MapPath获取绝对路径
string path = Server.MapPath("~/Temp/");
//获取一个布尔值,用于表示FileUpload控件是否已经包含一个文件
if(FileUpload1.HasFile)
{
//得到FileUpload中文件的扩展名
String fileExtension =System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
//定义一个数组来存放扩展名类型
String[] allowedExtensions = {".gif",".png","bmp","jpg" };
for (int i = 0; i < allowedExtensions.Length;i++)
{
//如果FileUpload1中的文件扩展名与存放数组扩展名中的之一匹配,fileOK的值为true
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
if (fileOK)
{
try
{
//调用 SaveAs方法时,必须指定服务器上用于保存上载文件的目录的完整路径。
FileUpload1.SaveAs(path + FileUpload1.FileName);
LabMessage1.Text = "文件上传成功";
//PostedFile获取一个与上传文件相关的HttpPostedFile对象,使用该对象可以获取上传文件的相关属性
LabMessage2.Text = "原文件路径:" + FileUpload1.PostedFile.FileName +"<br />" +
"文件大小:" + FileUpload1.PostedFile.ContentLength +"字节<br />" +
"文件类型:" + FileUpload1.PostedFile.ContentType + "<br/>";
}
catch (Exception ex)
{
LabMessage1.Text = "文件上传不成功";
}
}
else
{
LabMessage1.Text = "只能够上传图片文件";
}
}
}