ASP.NET 2.0 新控件 Fileupload
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 Upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//客户上传本地文件完全路径
string strFileFull = FileUpload1.PostedFile.FileName;
//上传文件名
string strFileName = FileUpload1.FileName;
//服务器用于存放上传文件的相对路径
string strSerPath = Server.MapPath("../Test/");
//存放上传文件的完全路径
string strFullName = strSerPath + "UploadFile\\" + strFileName;
//验证上传文件
if (FileUpload1.HasFile)
{
string strFileExtension = System.IO.Path.GetExtension(strFileFull);
string[] allowExtensions = { ".txt", ".jpg", ".gif", ".bmp", ".png" };
//扩展名验证
bool ExtensionOK = false;
for (int i = 0; i < allowExtensions.Length; i++)
{
if (strFileExtension == allowExtensions[i])
{
ExtensionOK = true;
break;
}
else
Label1.Text = "Unavailable file types.";
}
//文件名验证
bool NameOK = false;
if (!System.IO.File.Exists(strFullName))
NameOK = true;
else
Label1.Text = "File name exist. Please choose another file";
//上传文件
if (ExtensionOK == true && NameOK == true)
{
try
{
FileUpload1.SaveAs(strFullName);
Label1.Text = "Upload successful";
}
catch (Exception ex)
{
Label1.Text = "Upload Faild.";
}
}
else
Label1.Text = "Upload failed. " + Label1.Text;
}
else
{
Label1.Text = "";
}
}
}


浙公网安备 33010602011771号