在一个WEB应用系统中,经常需要用到文件上传功能,而在ASP中,要实现文件上传,需安装其他组件。而在Visual Studio.NET 2005中,微软内置了文件上传组件FileUpload,从而很方便地实现文件上传。
1、打开VS2005,创建一个新的网站test,打开默认页面default.aspx的设计视图,并加入三个基本构建FileUpload、Button和Label,ID分别为FileUpload1、Button1和Label1。
2、双击Button1,在default.aspx.cs文件中输入以下内容
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string strDir = FileUpload1.PostedFile.FileName;
int myPos = strDir.LastIndexOf("\\");
string strFileName = strDir.Substring(myPos);
string strPath = Server.MapPath(".") + strFileName;
this.Label1.Text = "保存路径:";
this.Label1.Text += strPath;
FileUpload1.PostedFile.SaveAs(strPath);
this.Label1.Text += "文件名称:";
this.Label1.Text += FileUpload1.PostedFile.FileName;
this.Label1.Text += "文件类型:";
this.Label1.Text += FileUpload1.PostedFile.ContentType;
this.Label1.Text += "文件大小:";
this.Label1.Text += FileUpload1.PostedFile.ContentLength.ToString();
}
}
3、测试,文件已成绩上传。