ASP.NET基本控件(1)——FileUpload控件
前台代码:
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="上传" onclick="btnUpload_Click" />
<asp:Literal ID="literal" runat="server" />
后台代码:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//判断是否上传了文件
if (fileUpload.HasFile)
{
//指定上传文件在服务器上的保存路径
string savePath = Server.MapPath("~/upload/");
//检查服务器上是否存在这个物理路径,如果不存在则创建
if (!System.IO.Directory.Exists(savePath))
{
System.IO.Directory.CreateDirectory(savePath);
}
savePath = savePath + "\\" + fileUpload.FileName;
fileUpload.SaveAs(savePath);
literal.Text = string.Format("<a href='upload/{0}'>upload/{0}</a>", fileUpload.FileName);
}
}
}