ASP.NET+C#环境中FileUpload控件的使用方法

长平狐 发布于 2012/06/08 09:49
阅读 2K+
收藏 0

本例是用该控件上传图片,上传其它附件依此类推

前台就随便拖一个FileUpload控件和一个button控件

1 <asp:FileUpload ID="FileUpload1" runat="server" /><br />
2 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

后台

View Code
1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Collections;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11
12 public partial class Manage_News_upload : System.Web.UI.Page
13 {
14 protected void Page_Load( object sender, EventArgs e)
15 {
16
17 }
18 protected void Button1_Click( object sender, EventArgs e)
19 {
20 if (FileUpload1.HasFile)
21 {
22 string fileExrensio = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower(); // ToLower转化为小写
23 string FileType = FileUpload1.PostedFile.ContentType;
24 string UploadURL = Server.MapPath( " ~/upload/ "); // 上传的目录
25 if (FileType == " image/bmp " || FileType == " image/gif " || FileType == " image/jpeg " || FileType == " image/jpg " || FileType == " image/png ") // 判断文件类型
26 {
27
28 try
29 {
30 if (!System.IO.Directory.Exists(UploadURL)) // 判断文件夹是否已经存在
31 {
32 System.IO.Directory.CreateDirectory(UploadURL); // 创建文件夹
33 }
34
35 FileUpload1.PostedFile.SaveAs(UploadURL + FileUpload1.FileName);
36 }
37 catch
38 {
39 Response .Write ( " 失败 ");
40 }
41 }
42 else
43 {
44 Response.Write( " 格式错误 ");
45 }
46 }
47 else
48 Response.Write( " 请选择文件 ");
49 }
50 }



 


原文链接:http://www.cnblogs.com/singlex/archive/2011/10/05/2199632.html
加载中
返回顶部
顶部