描述:在button事件中注册一个上传事件
代码详解:
protected void FileUpload_Click(object sender, EventArgs e)
{ bool fileIsvaild = false; //初始化一个bool型为false的fileIsvaild if (this.FileUpload1.HasFile)//哈希判读文件是否存在 { string fileExtension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();//获取文件名并转化为小写 string[] restrictExtension = { ".gif", ".jpg", "png", ".doc", ".txt" };//设置文件匹配格式 for (int i = 0; i < restrictExtension.Length; i++) { if (fileExtension == restrictExtension[i]) { fileIsvaild = true; } } if (fileIsvaild == true) { try { this.Image1.ImageUrl = "~/myfile/" + FileUpload1.FileName; //获取上传文件名 this.FileUpload1.SaveAs(Server.MapPath("~/myfile/") + FileUpload1.FileName);//保存文件 this.Label5.Text = "上传成功"; this.Label5.Text += "<br/>"; this.Label5.Text += FileUpload1.FileName + "<br/>"; this.Label5.Text += FileUpload1.FileBytes + "<br/>"; this.Label5.Text += FileUpload1.ControlStyle + "<br/>"; } catch (Exception ex) { this.Label5.Text = "无法上传" + ex.Message; } }}
else { Response.Write("<script>alert('上传的文件不存在!')</script>"); }}