ASP.NET (C#) FileUpload 上传功能

使用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

 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         }
Default.aspx.cs

 

转载于:https://www.cnblogs.com/codingmonkey/p/5919826.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值