教学思路ASP.Net之服务器控件: 四、FileUpload

在ASP.Net中如果想打开一个文件实现保存的效果,不能像Winform中使用openFileDialog控件,可以限制打开文件的类型,是否上传也必须通过另外一个控件的一个事件才能激发,如下Button2_Click.
winform中openFileDialog的使用方法如下,但是可参考性很少
openFileDialog1.Filter = "图片类型(*.jpg)|*.jpg";//限制打开文件的类型
            if (openFileDialog1.ShowDialog() == DialogResult.OK)  //根据对话框的选择结果判断是否上传
            {
                imageList1.Images.Add(Image.FromFile(openFileDialog1.FileName));//上传选中的文件
            }
下面就让我们来学习一下FileUpLoad控件
1 //上传图片
2         //TextBox2为上传图片的自定义文件名.
3         protected void Button2_Click( object sender, EventArgs e)
4         {
5                 if (FileUpload1.HasFile) //判读是否有文件
6                 {
7                         string filename = FileUpload1.FileName; //得到文件在本地的路径,及全路径
8                         string kzm = filename.Substring(filename.LastIndexOf ( ".")); //将扩展名存放到变量kzm中
9                         string uploadfilename = Server.MapPath( "upload") +"\\"+TextBox2.Text+kzm; //得到文件在服务器上的路径和文件名和扩展名。
10                         if (!kzm.Equals( ".jpg")&& kzm != ".JPG") //判断扩展名
11                                 Response.Write( "<script>alert('格式不正确');</script>");
12                         if (File.Exists(uploadfilename))                 //判断重名
13                                 Response.Write( "<script>alert('图片重名,请更换图片名称!');</script>");
14                         else
15                         {
16                                 try
17                                 {
18                                         FileUpload1.SaveAs(uploadfilename); //将文件上传到服务器上。
19                                         Image1.ImageUrl = "upload\\" + TextBox2.Text + kzm; //图片路径为刚才上传的文件
20                                         Image1.Height = 300; //控制图片的大小
21                                         Image1.Width =250;
22                                 }
23                                 catch(Exception ex)
24                                 {
25                                            Response .Write ( "<script>alert('"+ex.Message.ToString ()+ "');</script>");
26                                 }
27                         }
28                 }
29                 else
30                 {
31                         Response.Write( "<script>alert('你还没选择上传的图片!');</script>");
32            
33                 }
34         }
下面的代码为在客户端书写对于上传控件文本格式的验证方法:
< %@ Page Language ="C#" AutoEventWireup ="true" CodeFile ="Upload.aspx.cs" Inherits ="Upload" % >

< !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 >Asp.net文件上传时的客户端简单验证 </title>
        
< script language ="javascript" >
function checkmes(id)
{
     var filename = document.getElementById(id).value;
     //验证是否选择文件
     if(filename=="")
     {
         alert("请选择一个文件!");
         return false;
     }
        
     //验证扩展名
     var ex = filename.substring(filename.length-4);
     if(ex!=".xls")
     {
            alert("你选择的文件类型不正确,请选择一个Excel文件!");
            return false;
     }
        
     //最后提示信息
     return confirm("你确定要上传此Excel文件?");
}
</script>

</head>
< body >
         < form id ="form1" runat ="server" >
         < div >
                 < strong >Asp.net文件上传时的客户端简单验证 < br />
                         < br />
                         < asp:FileUpload ID ="fu_Excel" runat ="server" Width ="300px" /> 
                         < asp:Button ID ="btn_Upload" runat ="server" Text ="上 传" OnClick ="btn_Upload_Click" />  </strong> </div>
         </form>
</body>
</html>
在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 Upload : System.Web.UI.Page
{
         protected void Page_Load( object sender, EventArgs e)
     {
                btn_Upload.Attributes.Add( "onclick", "javascript:return checkmes('" + fu_Excel.ClientID + "');");
        }

         protected void btn_Upload_Click( object sender, EventArgs e)
    {
                 //上传文件的服务器端代码
        }
}
对于上传文件的验证方式还可以采用ASP.Net中的验证控件,如下便是对于照片格式的验证方式。
< asp:FileUpload ID ="FileUpload1" runat ="server" />
                                                                 < asp:RegularExpressionValidator        
id ="FileUpLoadValidator" runat ="server"        
ErrorMessage ="上传图片只能为.jpg或.gif"        
ValidationExpression ="^([a-zA-Z]:\\)[0-9a-zA-Z\u4e00-\u9fa5\w\s\\!@#\$%^&\*\(\)_\+\-=\[\]{};'\,\.]*(.jpg|.JPG|.gif|.GIF|.bmp|.BMP)$"        

ControlToValidate ="FileUpload1" > </ asp:RegularExpressionValidator >
如果想改变上传文件的大小限制,要在config文件中,在  <system.web/> 节点内加入如下节点及其属性
 <httpRuntime executionTimeout ="90" maxRequestLength="4096"/> 
批量上传:
1protected void Button3_Click( object sender, EventArgs e)
2        {
3                HttpFileCollection fileuploadControls = Request.Files;
4                 for ( int i = 0; i < fileuploadControls.Count; i++)
5                {
6                        HttpPostedFile fileuploadcontrol = fileuploadControls[i];
7                         if (fileuploadControls[i].ContentLength > 0)
8                        {
9                                 try
10                                {
11                                        fileuploadcontrol.SaveAs(Server.MapPath( "upload") +"\\"+Path.GetFileName( fileuploadControls[i].FileName));
12                                }
13                                 catch (Exception ex)
14                                {
15                                        Response.Write( "<script>alert('" + ex.Message.ToString() + "');</script>");
16                                }
17                        }
18                }
19                Response.Write( "<script>alert('上传成功!');</script>");
20        }

本文出自 “叶子文文” 博客,转载请与作者联系!

你可能感兴趣的:(职场,fileupload,asp.net,休闲,服务器控件)