C# 上传文件

webconfig 配置

<!--文件上传类型-->

<add key="FileType" value=".doc,.xls,.txt,.rar"/>

<add key="PicTureTye" value=".jpg|.gif|.png|.bmp|.psd|.svg|"/>

<!--上传文件大小-->

<add key="FileSizeLimit" value="102400"/>

#region 判断上传文件类型

protected bool IsAllowableFileType()

{

//从web.config读取判断文件类型限制

string strFileTypeLimit = ConfigurationManager.AppSettings["FileType"].ToString();

//当前文件扩展名是否包含在这个字符串中

if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUp.FileName).ToLower()) != -1)

{

return true;

}

else

return false;

}

protected bool IsAllowablePictureType()

{

//从web.config读取判断图片类型限制

string strFileTypeLimit = ConfigurationManager.AppSettings["PicTureTye"].ToString();

//当前文件扩展名是否包含在这个字符串中

if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUp.FileName).ToLower()) != -1)

{

return true;

}

else

return false;

}

#endregion

#region 判断文件大小限制

private bool IsAllowableFileSize()

{

//从web.config读取判断文件大小的限制

double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]) * 1024;

//判断文件是否超出了限制

if (iFileSizeLimit > FileUp.PostedFile.ContentLength)

{

return true;

}

else

{

return false;

}

}

#endregion

protected void btnUpFile_Click(object sender, EventArgs e)

{

//判读是否有上传文件

if (FileUp.PostedFile.ContentLength > 0)

{

if (IsAllowableFileType())

{

if (Directory.Exists(Server.MapPath("~/File")) == false)//判断文件夹是否存在,若不存在则创建

{

Directory.CreateDirectory(Server.MapPath("~/File"));

}

else

if (IsAllowableFileSize())

{

//string UploadFilePath = ConfigurationManager.AppSettings["UploadFile"].ToString();

string UploadFilePath = Server.MapPath("File\\");

string fullName = FileUp.PostedFile.FileName;

string newName = DateTime.Now.Ticks.ToString() + fullName.Substring(fullName.LastIndexOf("."));

FileUp.SaveAs(UploadFilePath + newName);

lblFileUrl.Text = fullName.Substring(fullName.LastIndexOf("\\")) + " 上传成功";

lblSaveFileName.Text = newName;

}

else

MessegeBox.Show(this, "文件太大了,上传失败");

}

else

MessegeBox.Show(this, "文件类型不正确,上传失败");

}

else

{

MessegeBox.Show(this, "上传文件为空,上传失败");

}

}

到这里,文件已经上传到一个File文件夹中了,当然,如果要把路径保存到数据库,你需要另外写一个保存路径到数据库的方法,在此就不在赘述了。

如果有需要保存入数据库的方法,给我留言,我会回复.