using ......
/// <summary>
/// upLoad 的摘要说明
/// </summary>
public class upLoad
{
public upLoad()
{
}
/// <summary>
/// 根目录
/// </summary>
protected string uploadVirtualPath = "";
/// <summary>
/// 上传文件类型数组
/// </summary>
protected string[] uploadExt;
/// <summary>
/// 上传附件路径
/// </summary>
protected string uploadPath;
/// <summary>
/// 上传文件大小
/// </summary>
private Int32 fileLength;
/// <summary>
/// 上传文件名称
/// </summary>
private string filename;
/// <summary>
/// 上传时间
/// </summary>
private DateTime uploadDate;
/// <summary>
/// 是否上传成功
/// </summary>
private bool isUpload;
#region 文件上传操作
/// <summary>
/// 进行文件上传操作,并将上传文件信息返回
/// </summary>
/// <param name="myFiles">所有上传文件</param>
/// <param name="p">页面</param>
/// <returns>上传文件信息的实体</returns>
public bool uploadFile(System.Web.HttpFileCollection myFiles,System.Web.UI.Page p,Attachment att1)
{
try
{
//初始化上传配置
this.loadConfig(p);
//存放是否是规定上传类型
bool accepUpload = true;
for (int i = 0; i < myFiles.Count; i++)
{
accepUpload = true;
System.Web.HttpPostedFile postedFile = myFiles[i];
//上传文件大小
this.fileLength = postedFile.ContentLength;
//上传文件名
this.filename = Path.GetFileName(postedFile.FileName);
//如果没有选择上传文件,或者上传控件没有选择上传,将继续下次循环,这里是防止用户在多文件上传是,其中有空的
if (filename.Equals("") || filename == null)
{
continue;
}
//上传文件的扩展名
string fileExtecsion = Path.GetExtension(postedFile.FileName);
for (int j = 0; j < this.uploadExt.Length; j++)
{
//判断上传文件是否是在规定的类型
if (fileExtecsion.Equals("." + this.uploadExt[j]))
{
//将检查结果存放
accepUpload = false;
}
}
if (accepUpload)
{
//上传文件写入规定目录
postedFile.SaveAs(this.uploadPath + "/" + this.filename);
//保存到附件表中
Attachment att = new Attachment();
att.open();
att.FilePath = this.uploadPath + "/" + this.filename;
att.FileSize = this.fileLength;
att.FileName = this.filename;
att.UploadDate = DateTime.Now;
att.Type = att1.Type;
att.Description = att1.Description;
att.InfoId = att1.InfoId;
att.save();
}
}
}
catch (Exception exl)
{
Console.Write(exl.Message);
return false;
}
return true;
}
#endregion
#region 上传文件初始化配置
/// <summary>
/// 上传文件初始化配置
/// </summary>
public void loadConfig(System.Web.UI.Page p)
{
//读取上传存放位置路径
this.uploadVirtualPath = ConfigurationManager.AppSettings["uploadPath"];
//组成,上传文件路径位置
this.uploadPath = p.Server.MapPath(this.uploadVirtualPath) + newPath();
//上传路径文件夹是否存在
if (!Directory.Exists(uploadPath))
{
//不存在创建文件夹
Directory.CreateDirectory(uploadPath);
}
//获取上传指定上传文件类型
string ext = ConfigurationManager.AppSettings["noExt"];
//存放入数组中
this.uploadExt = ext.Split(',');
}
#endregion
#region 创建上传文件夹
/// <summary>
/// 将上传文件创建文件夹,用当前日期存放
/// </summary>
/// <returns></returns>
public String newPath()
{
DateTime datetime = DateTime.Now;
return datetime.ToString("yyyy-MM-dd");
}
#endregion
}
**********************************************
web.config配置里面这样写
<appSettings>
<add key="uploadPath" value="~/upload/"/>
<add key="noExt" value="exe,js,asp,aspx"/>
</appSettings>