使用FileUpload控件实现文件传送至服务器这一功能
————————————Default.aspx源码————————————
//本集使用FileUpload控件实现文件浏览、Button控件进行触发、image实现文件图片显示、label显示文件相关信息
<%@ Page Language="C#" CodeFile="Default.aspx.cs"Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1"runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="Button1" runat="server"OnClick="Button1_Click" Text="上 传" Width="54px"/>
<asp:Label ID="Label1" runat="server" Height="16px"Style="z-index: 100; left: 15px;
position: absolute; top: 156px"Width="89px"></asp:Label>
<asp:Image ID="Image1" runat="server"ImageUrl="~/images/服饰1.gif" Style="z-index: 102;
left: 20px; position: absolute; top: 49px" Width="73px"/>
</div>
</form>
</body>
</html>
——————————————cs代码——————————————
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
}
protectedvoid Button1_Click(object sender, EventArgs e)
{
bool fileIsValid = false;
//如果确认了文件上传,则判断文件类型是否符合要求
if (this.FileUpload1.HasFile)
{
//获取上传文件的后缀名
String fileExtension =System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();//ToLower是将Unicode字符的值转换成它的小写等效项
//定义一个数组,把文件后缀名的的类型总结出来
String[] restrictExtension ={ ".jpg",".gif",".bmp",".png"};
//判断文件类型是否符合要求
for (int i = 0; i < restrictExtension.Length;i++)
{
if (fileExtension == restrictExtension[i])
{
fileIsValid = true;
}
}
}
//如果文件类型符合要求,则用SaveAs方法实现上传,并显示信息
if (fileIsValid == true)
{
try
{
this.Image1.ImageUrl = "~/images/" + FileUpload1.FileName;
this.FileUpload1.SaveAs(Server.MapPath("~/images/") +FileUpload1.FileName);
this.Label1.Text = "文件上传成功";
this.Label1.Text += "<br/>";
this.Label1.Text += "<li>" + "源文件路径:"+ this.FileUpload1.PostedFile.FileName;
this.Label1.Text += "<li>" + "文件大小:"+ this.FileUpload1.PostedFile.ContentLength + "字节";
this.Label1.Text += "<br/>";
this.Label1.Text += "<li>" + "文件类型:"+ this.FileUpload1.PostedFile.ContentType;
}
catch
{
this.Label1.Text = "文件上传不成功";
}
finally
{
}
}
else
{
this.Label1.Text = "文件的后缀名只能为.jpg、.gif、.bmp、.png";
}
}
}
PS:1.获取文件的相关知识
string filePath = FileUpload1.PostedFile.FileName;//获取上传文件的路径
string fileName = filePath.Substring(filePath.LastIndexOf("\\")+1);//获取文件名称
string fileSize = Convert.ToString(FileUpload1.PostedFile.ContentLength);//获取文件大小
string fileType = FileUpload1.PostedFile.ContentType;//获取文件类型
string serverPath = Server.MapPath("指定文件夹名称")+fileName;//保存服务器的路径
FileUpLoad1.PostedFile.SaveAs(serverPath);//确定文件上传