asp.net fileupload控件上传文件
1、文件类型验证
复制代码 代码示例:
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 = "没有选择要上传的文件!";
}
}
2、上传文件代码:
复制代码 代码示例:
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 = "没有选择要上传的文件!";
}
}
3、上传限制:asp.net FileUpload控件实现文件格式判断与文件大小限制
复制代码 代码示例:
<system.web>
<httpRuntime maxRequestLength="40690" executionTimeout="6000" />
</system.web>
maxRequestLength表示可上传文件的最大值
executiontimeout表示asp.net关闭前允许发生的上载秒数。