ASP.NET+C#环境中FileUpload控件的使用方法
本例是用该控件上传图片,上传其它附件依此类推
前台就随便拖一个FileUpload控件和一个button控件
1 <asp:FileUpload ID="FileUpload1" runat="server" /><br />
2 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
后台
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }
作者:VShawn
出处:http://www.cnblogs.com/singlex/
本文版权归作者所有,欢迎转载,但未经博客作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。