Asp.net fileupload用法
![](http://www.webweb.com/aff_banner2.gif)
文件类型验证
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExt == ".jpg" || fileExt == ".gif")
{
try
{
FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);
Label1.Text = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +
"文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +
"文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +
"文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" +
"文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +
"保存路径:" + Server.MapPath("upload") + "\\" + FileUpload1.FileName;
}
catch (Exception ex)
{
Label1.Text = "发生错误:" + ex.Message.ToString();
}
}
else
{
Label1.Text = "只允许上传jpg、gif文件!";
}
}
else
{
Label1.Text = "没有选择要上传的文件!";
}
}
上传
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);
Label1.Text = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +
"文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +
"文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +
"文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" +
"文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +
"保存路径:" + Server.MapPath("upload") + "\\" + FileUpload1.FileName;
}
catch (Exception ex)
{
Label1.Text = "发生错误:" + ex.Message.ToString();
}
}
else
{
Label1.Text = "没有选择要上传的文件!";
}
}
补充上传限制
<system.web>
<httpRuntime maxRequestLength="40690" executionTimeout="6000" />
</system.web>
maxRequestLength表示可上传文件的最大值,executionTimeout表示ASP.NET关闭前允许发生的上载秒数。