zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#通用文件上传类

2023-06-13 09:14:15 时间
1、Upfile.aspx:
复制代码代码如下:

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Upfile.aspx.cs"Inherits="Inc_Upfile"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
<htmlxmlns="http://www.w3.org/1999/xhtml";>
<headrunat="server">
<title>上传文件</title>
<linkhref="../Manage/Style.Css"type="text/css"rel=Stylesheet/>
</head>
<body>
<formid="form1"runat="server">
<divstyle="left:0px;clip:rect(0pxautoauto0px);position:absolute;top:0px">
<asp:FileUploadID="FileUpload1"runat="server"/>
<asp:ButtonID="Button1"runat="server"OnClick="Button1_Click"Text="上传文件"CssClass="btn2"/>
<asp:LabelID="Label1"runat="server"Text="Label"></asp:Label></div>
</form>
</body>
</html>

Upfile.aspx.cs

代码
复制代码代码如下:

usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
publicpartialclassInc_Upfile:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
//CutBy梦溪苑。
}
protectedvoidButton1_Click(objectsender,EventArgse)
{
AllSheng.uploadUpFiles=newAllSheng.upload();
//HttpPostedFileFile=FileUpload1.PostedFile;
//AllSheng.UploadObj.PhotoSave("/",FileUpload1);
HttpFileCollectionfiles=HttpContext.Current.Request.Files;
UpFiles.Path="../UpLoadfiles";
StringReStr=UpFiles.SaveAs(files).ToString();
Label1.Text=ReStr;
UpFiles=null;
}
}

3、类文件:

代码
复制代码代码如下:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
/**////<summary>
///Cls_Upfile的摘要说明
///</summary>
///
namespaceAllSheng
{
publicclassupload
{
变量#region变量
System.Web.HttpPostedFilepostedFile;
protectedstringlocalFileName;//原文件名(含扩展名)
protectedstringlocalFileExtension;//原扩展名
protectedlonglocalFileLength;//原文件大小
protectedstringlocalFilePath;//原文件路径
protectedstringsaveFileName;//保存的文件名(含扩展名)
protectedstringsaveFileExtension;//保存的扩展名
//protectedlongsaveFileLength;//保存的文件大小
protectedstringsaveFilePath;//保存文件的服务器端的完整路径
protectedstringsaveFileFolderPath;//保存文件的服务器端的文件夹路径
privatestringpath=null;
privatestringfileType=null;
privateintsizes=0;
#endregion
upload():初始化变量#regionupload():初始化变量
/**////<summary>
///初始化变量
///</summary>
publicupload()
{
path=@"uploadimages";//上传路径
fileType="jpg|gif|bmp|jpeg|png|rar|doc";
sizes=200;//传文件的大小,默认200KB
}
#endregion
设置传入的值:Path/Sizes/FileType#region设置传入的值:Path/Sizes/FileType
/**////<summary>
///设置上传路径,如:uploadimages
///</summary>
publicstringPath
{
set
{
path=@""+value+@"";
}
}
/**////<summary>
///设置上传文件大小,单位为KB
///</summary>
publicintSizes
{
set
{
sizes=value;
}
}
/**////<summary>
///设置上传文件的类型,如:jpg|gif|bmp
///</summary>
publicstringFileType
{
set
{
fileType=value;
}
}
#endregion
SaveAs()上传文件#regionSaveAs()上传文件
publicstringSaveAs(System.Web.HttpFileCollectionfiles)
{
stringmyReturn="";
try
{
for(intiFile=0;iFile<files.Count;iFile++)
{
postedFile=files[iFile];
//获得文件的上传的路径
localFilePath=postedFile.FileName;
//判断上传文件路径是否为空
if(localFilePath==null||localFilePath=="")
{
//message("您没有上传数据呀,是不是搞错了呀!");
//break;
continue;
}
else
{
判断文件大小#region判断文件大小
//获得上传文件的大小
localFileLength=postedFile.ContentLength;
//判断上传文件大小
if(localFileLength>=sizes*1024)
{
message("上传的图片不能大于"+sizes+"KB");
break;
}
#endregion
文件夹#region文件夹
//获取保存文件夹路径
saveFileFolderPath=getSaveFileFolderPath(path);
#endregion
文件名#region文件名
//获得原文件名(含扩展名)
localFileName=System.IO.Path.GetFileName(postedFile.FileName);
saveFileName=DateTime.UtcNow.ToString("yyyy"+"MM"+"dd"+"HH"+"mm"+"ss"+"ffffff");//"yyyy"+"MM"+"dd"+"HH"+"mm"+"ss"+"ffffff"
#endregion
扩展名#region扩展名
//获取原文件扩展名
localFileExtension=getFileExtension(localFileName);
//如果为真允许上传,为假则不允许上传
if(localFileExtension=="")
{
message("目前本系统支持的格式为:"+fileType);
}
//得到保存文件的扩展名,可根据需要更改扩展名
saveFileExtension=localFileExtension;
#endregion
//得到保存文件的完整路径
saveFilePath=saveFileFolderPath+saveFileName+saveFileExtension;
postedFile.SaveAs(saveFilePath);
myReturn=myReturn+((myReturn==""||myReturn==null)?"":"|")+path.TrimStart(newchar[]{""})+saveFileName+saveFileExtension;
//以下对文章的内容进行一些加工
System.Web.HttpContext.Current.Response.Write("<script>parent.Article_Content___Frame.FCK.EditorDocument.body.innerHTML+="<imgsrc="+saveFileName+saveFileExtension+""+"border=0/>"</SCRIPT>");
}
}
}
catch
{
//异常
message("出现未知错误!");
myReturn=null;
}
returnmyReturn;
}
#endregion
getSaveFileFolderPath():获得保存的文件夹的物理路径#regiongetSaveFileFolderPath():获得保存的文件夹的物理路径
/**////<summary>
///获得保存的文件夹的物理路径
///返回保存的文件夹的物理路径,若为null则表示出错
///</summary>
///<paramname="format">保存的文件夹路径或者格式化方式创建保存文件的文件夹,如按日期"yyyy"+"MM"+"dd":20060511</param>
///<returns>保存的文件夹的物理路径,若为null则表示出错</returns>
privatestringgetSaveFileFolderPath(stringformat)
{
stringmySaveFolder=null;
try
{
stringfolderPath=null;
//以当前时间创建文件夹,
//!!!!!!!!!!!!以后用正则表达式替换下面的验证语句!!!!!!!!!!!!!!!!!!!
if(format.IndexOf("yyyy")>-1||format.IndexOf("MM")>-1||format.IndexOf("dd")>-1||format.IndexOf("hh")>-1||format.IndexOf("mm")>-1||format.IndexOf("ss")>-1||format.IndexOf("ff")>-1)
{
//以通用标准时间创建文件夹的名字
folderPath=DateTime.UtcNow.ToString(format);
mySaveFolder=System.Web.HttpContext.Current.Server.MapPath(".")+@""+folderPath+@"";
}
else
{
mySaveFolder=System.Web.HttpContext.Current.Server.MapPath(".")+format;
}
System.IO.DirectoryInfodir=newSystem.IO.DirectoryInfo(mySaveFolder);
//判断文件夹否存在,不存在则创建
if(!dir.Exists)
{
dir.Create();
}
}
catch
{
message("获取保存路径出错");
}
returnmySaveFolder;
}
#endregion
getFileExtension():获取原文件的扩展名#regiongetFileExtension():获取原文件的扩展名
/**////<summary>
///获取原文件的扩展名,返回原文件的扩展名(localFileExtension),该函数用到外部变量fileType,即允许的文件扩展名.
///</summary>
///<paramname="myFileName">原文件名</param>
///<returns>原文件的扩展名(localFileExtension);若返回为null,表明文件无后缀名;若返回为"",则表明扩展名为非法.</returns>
privatestringgetFileExtension(stringmyFileName)
{
stringmyFileExtension=null;
//获得文件扩展名
myFileExtension=System.IO.Path.GetExtension(myFileName);//若为null,表明文件无后缀名;
//分解允许上传文件的格式
if(myFileExtension!="")
{myFileExtension=myFileExtension.ToLower();//转化为小写
}
string[]temp=fileType.Split("|");
//设置上传的文件是否是允许的格式
boolflag=false;
//判断上传的文件是否是允许的格式
foreach(stringdataintemp)
{
if(("."+data)==myFileExtension)
{
flag=true;
break;
}
}
if(!flag)
{
myFileExtension="";//不能设置成null,因为null表明文件无后缀名;
}
returnmyFileExtension;
}
#endregion
message():弹出消息框#regionmessage():弹出消息框
/**////<summary>
///弹出消息框,显示内容(msg),点击"确定"后页面跳转到该路径(url)
///</summary>
///<paramname="msg">显示内容</param>
///<paramname="url">跳转路径</param>
privatevoidmessage(stringmsg,stringurl)
{
System.Web.HttpContext.Current.Response.Write("<scriptlanguage=javascript>alert(""+msg+"");window.location=""+url+""</script>");
}
/**////<summary>
///弹出消息框,显示内容(msg),无跳转
///</summary>
///<paramname="msg">显示内容</param>
privatevoidmessage(stringmsg)
{
System.Web.HttpContext.Current.Response.Write("<scriptlanguage=javascript>alert(""+msg+"");</script>");
}
#endregion
}
}