使用ASP.NET的 FileLoad 控件, 实现向服务器上传文件的功能:
Default.aspx
1 <body> 2 <form id="form1" runat="server"> 3 <asp:Label ID="Label3" runat="server" Style="color: Red" Text="*"></asp:Label> 4 <asp:Label ID="Label2" runat="server" Text="上传文件:"></asp:Label> 5 <asp:FileUpload ID="FileUpload1" runat="server" BorderStyle="Double" Width="426px" /> 6 <asp:Button ID="BtnUpload" runat="server" Text="上传" OnClick="BtnUpload_Click" /> 7 <asp:Label ID="Label1" runat="server" Text="" Style="color: Red"></asp:Label> 8 </form> 9 </body>
Default.aspx.cs
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 protected void BtnUpload_Click(object sender, EventArgs e) 2 { 3 Boolean fileOk = false; 4 string path = Server.MapPath("~/REPORT/Templates/"); 5 6 if (FileUpload1.HasFile) 7 { 8 // 取得文件的扩展名,并转换成小写 9 string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower(); 10 // 限定只能上传.xls/.xlsx 11 string[] allowExtension = { ".xls" , ".xlsx"}; 12 //对上传的文件的类型进行一个个匹对 13 for (int i = 0; i < allowExtension.Length; i++) 14 { 15 if (fileExtension == allowExtension[i]) 16 { 17 fileOk = true; 18 break; 19 } 20 } 21 // 22 if (!fileOk) 23 { 24 Label1.Text = "要上传的文件类型不对!"; 25 } 26 27 if (fileOk) 28 { 29 try 30 { 31 //如果不存在就创建文件夹 32 if (System.IO.Directory.Exists(path) == false) 33 { 34 System.IO.Directory.CreateDirectory(path); 35 } 36 37 FileUpload1.SaveAs(path + FileUpload1.FileName); 38 Label1.Text = "上传成功!"; 39 } 40 catch 41 { 42 Label1.Text = "上传失败!"; 43 } 44 } 45 } 46 else 47 { 48 Label1.Text = "请选择文件路径!"; 49 } 50 }