ASP.NET(C#)FileUpload实现上传限定类型和大小的文件
(2010-05-14 13:23:01)ASP.NET内置了FileUpload这个上传控件.
其属性主要包括:
ContenLength:上传文件大小,单位:字节
FileName:文件名称
HasFile:是否选择了文件
SaveAs():保存上传文件的内容
default.aspx
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 id="form1" runat="server"> <div> <asp:FileUpload ID="FileUpload" runat="server" /> <br/> <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="上传" /><br/>
<asp:Label ID="labresult" runat="server"></asp:Label> </div>
</form> </body> </html>
default.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 _Default : System.Web.UI.Page
{ protected void Page_Load(object sender, EventArgs e) { } protected void btnUpload_Click(object sender, EventArgs e) { Boolean fileOk = false; string path = Server.MapPath("~/upload/"); //判断是否已经选取文件 if (FileUpload.HasFile) { //取得文件的扩展名,并转换成小写 string fileExtension = System.IO.Path.GetExtension(FileUpload.FileName).ToLower(); //限定只能上传jpg和gif图片 string[] allowExtension = { ".jpg", ".gif", ".txt", ".xls" }; //对上传的文件的类型进行一个个匹对 for (int i = 0; i < allowExtension.Length; i++) { if (fileExtension == allowExtension[i]) { fileOk = true; break; } } if (fileOk) { labresult.Text = "要上传的文件类型不对!"; }//对上传文件的大小进行检测,限定文件最大不超过2M
if (FileUpload.PostedFile.ContentLength > 2048000) { fileOk = false; } //最后的结果 if (fileOk) { try { FileUpload.PostedFile.SaveAs(path + FileUpload.FileName); labresult.Text ="上传成功"; } catch {labresult.Text = "上传失败";
} } else { labresult.Text = "文件类型或者文件大小超出2M或者文件类型不对";}
}
} }