//单击事件,完成上传文件到服务器
private void btnUpload_Click(object sender, System.EventArgs e)
{
if(fileUpload1.PostedFile!=null && fileUpload1.PostedFile.FileName!="" && fileUpload1.PostedFile.ContentLength!=0)
{
if(fileUpload1.PostedFile.ContentLength > 5 * 1024 )
{
lblError.Text = "上传文件过大";
lblError.Visible = true;
return;
}
string sFileName = Path.GetExtension(fileUpload1.PostedFile.FileName).ToUpper();
if(! (strFileName == ".BMP" || strFileName == ".GIF" || strFileName == ".JPG") )
{
lblError.Text = "文件格式不正确";
lblError.Visible = true;
return;
}
Random ran = new Random();
string sNewImg = DateTime.Now.ToString(@"yyyyMMddHHmmss") + ran.Next(100,999) + Path.GetExtension(fileUpload1.PostedFile.FileName) ;
string sPath = Server.MapPath( "~/Picture/" + sNewImg);
if( !Directory.Exists(Path.GetDirectoryName(sPath) ) )
{
Directory.CreateDirectory(Path.GetDirectoryName(strPath));
}
fileUpload1.PostedFile.SaveAs(sPath);
}
}
其中,"fileUpload1.PostedFile.FileName"便是文本框中的路径!
private void btnUpload_Click(object sender, System.EventArgs e)
{
if(fileUpload1.PostedFile!=null && fileUpload1.PostedFile.FileName!="" && fileUpload1.PostedFile.ContentLength!=0)
{
if(fileUpload1.PostedFile.ContentLength > 5 * 1024 )
{
lblError.Text = "上传文件过大";
lblError.Visible = true;
return;
}
string sFileName = Path.GetExtension(fileUpload1.PostedFile.FileName).ToUpper();
if(! (strFileName == ".BMP" || strFileName == ".GIF" || strFileName == ".JPG") )
{
lblError.Text = "文件格式不正确";
lblError.Visible = true;
return;
}
Random ran = new Random();
string sNewImg = DateTime.Now.ToString(@"yyyyMMddHHmmss") + ran.Next(100,999) + Path.GetExtension(fileUpload1.PostedFile.FileName) ;
string sPath = Server.MapPath( "~/Picture/" + sNewImg);
if( !Directory.Exists(Path.GetDirectoryName(sPath) ) )
{
Directory.CreateDirectory(Path.GetDirectoryName(strPath));
}
fileUpload1.PostedFile.SaveAs(sPath);
}
}
其中,"fileUpload1.PostedFile.FileName"便是文本框中的路径!
本文详细阐述了在ASP.NET环境中实现文件上传至服务器的过程,包括验证文件大小、类型,以及文件保存路径的设置。

824

被折叠的 条评论
为什么被折叠?



