文件上传的代码:
protected void Page_Load(object sender, EventArgs e)
{
//HttpFileCollection files = HttpContext.Current.Request.Files;
状态信息
//System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
//for (int ifile = 0; ifile < files.Count; ifile++)
//{
// HttpPostedFile postedfile = files[ifile];
// string filename, fileExt;
// filename = System.IO.Path.GetFileName(postedfile.FileName); //获取文件名
// fileExt = System.IO.Path.GetExtension(filename); //获取文件后缀
// int MaxAllowUploadFileSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MaxAllowUploadFileSize"]); //定义允许上传文件大小
// if (MaxAllowUploadFileSize == 0) { MaxAllowUploadFileSize = 26500; }
// string allowexts = System.Configuration.ConfigurationManager.AppSettings["AllowUploadFileType"];
// //定义允许上传文件类型
// if (allowexts == "") { allowexts = "doc|docx|rar|xls|xlsx|txt"; }
// Regex allowext = new Regex(allowexts);
// if (postedfile.ContentLength < MaxAllowUploadFileSize && allowext.IsMatch(fileExt)) //检查文件大小及扩展名
// {
// postedfile.SaveAs(Server.MapPath("upload\\" + filename + fileExt)); //upload为与本页面同一目录,可自行修改
// }
// else
// {
// Response.Write("<script>alert('不允许上传类型" + fileExt + "或文件过大')</script>");
// }
//}
protected void btupload_Click(object sender, EventArgs e)
{
bool fileIsValid = false;
if (this.FileUpload1.HasFile)
{
String fileExtension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();//获取文件扩展名
String[] restricExtension = { ".xls", ".doc", ".txt" }; //限制上传类型
for (int i = 0; i < restricExtension.Length; i++)
{
if (fileExtension == restricExtension[i])
{ fileIsValid = true; }
}
if (fileIsValid == true && this.FileUpload1.PostedFile.ContentLength <= 1e20)
{
try
{
this.imgDisplay.ImageUrl = "~/WebSite1/" + FileUpload1.FileName;
this.FileUpload1.SaveAs(Server.MapPath("~/upfiles/") + FileUpload1.FileName);
this.Label1.Text = "文件上传成功";
this.Label1.Text += "<Br/>";
this.Label1.Text += "<li>" + "原文件路径:" + this.FileUpload1.PostedFile.FileName;
this.Label1.Text += "<Br/>";
this.Label1.Text += "<li>" + "文件大小:" + this.FileUpload1.PostedFile.ContentLength + "字节";
this.Label1.Text += "<Br/>";
this.Label1.Text += "<li>" + "文件类型:" + this.FileUpload1.PostedFile.ContentType;
}
catch
{
this.Label1.Text = "文件上传不成功!";
}
finally { }
}
else
{
this.Label1.Text = "只能上传后缀为.xls,.doc,.txt的文件";
}
}
}