C# 通用文件上传类
程序员文章站
2024-03-08 13:54:04
1、upfile.aspx: 复制代码 代码如下: <%@ page language="c#" autoeventwireup="true" codefile="u...
1、upfile.aspx:
<%@ page language="c#" autoeventwireup="true" codefile="upfile.aspx.cs" inherits="inc_upfile" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd";>
<html xmlns="http://www.w3.org/1999/xhtml"; >
<head runat="server">
<title>上传文件</title>
<link href="../manage/style.css" type="text/css" rel=stylesheet />
</head>
<body>
<form id="form1" runat="server">
<div style="left: 0px; clip: rect(0px auto auto 0px); position: absolute; top: 0px">
<asp:fileupload id="fileupload1" runat="server" />
<asp:button id="button1" runat="server" onclick="button1_click" text="上传文件" cssclass="btn2" />
<asp:label id="label1" runat="server" text="label"></asp:label></div>
</form>
</body>
</html>
upfile.aspx.cs
代码
using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
public partial class inc_upfile : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
//cut by 梦溪苑。
}
protected void button1_click(object sender, eventargs e)
{
allsheng.upload upfiles = new allsheng.upload();
//httppostedfile file = fileupload1.postedfile;
// allsheng.uploadobj.photosave("/", fileupload1);
httpfilecollection files = httpcontext.current.request.files;
upfiles.path = "../uploadfiles";
string restr= upfiles.saveas(files).tostring();
label1.text = restr;
upfiles = null;
}
}
3、类文件:
代码
using system;
using system.data;
using system.configuration;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
/**//// <summary>
/// cls_upfile 的摘要说明
/// </summary>
///
namespace allsheng
{
public class upload
{
变量#region 变量
system.web.httppostedfile postedfile;
protected string localfilename;//原文件名(含扩展名)
protected string localfileextension;//原扩展名
protected long localfilelength;//原文件大小
protected string localfilepath;//原文件路径
protected string savefilename;//保存的文件名(含扩展名)
protected string savefileextension;//保存的扩展名
//protected long savefilelength;//保存的文件大小
protected string savefilepath;//保存文件的服务器端的完整路径
protected string savefilefolderpath;//保存文件的服务器端的文件夹路径
private string path = null;
private string filetype = null;
private int sizes = 0;
#endregion
upload():初始化变量#region upload():初始化变量
/**//// <summary>
/// 初始化变量
/// </summary>
public upload()
{
path = @"uploadimages"; //上传路径
filetype = "jpg|gif|bmp|jpeg|png|rar|doc";
sizes = 200; //传文件的大小,默认200kb
}
#endregion
设置传入的值:path/sizes/filetype#region 设置传入的值:path/sizes/filetype
/**//// <summary>
/// 设置上传路径,如:uploadimages
/// </summary>
public string path
{
set
{
path = @"" + value + @"";
}
}
/**//// <summary>
/// 设置上传文件大小,单位为kb
/// </summary>
public int sizes
{
set
{
sizes = value;
}
}
/**//// <summary>
/// 设置上传文件的类型,如:jpg|gif|bmp
/// </summary>
public string filetype
{
set
{
filetype = value;
}
}
#endregion
saveas()上传文件#region saveas()上传文件
public string saveas(system.web.httpfilecollection files)
{
string myreturn = "";
try
{
for (int ifile = 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(new char[] { '' }) + savefilename + savefileextension;
//以下对文章的内容进行一些加工
system.web.httpcontext.current.response.write("<script>parent.article_content___frame.fck.editordocument.body.innerhtml+='<img src=" + savefilename + savefileextension + " "+" border=0 />'</script>");
}
}
}
catch
{
//异常
message("出现未知错误!");
myreturn = null;
}
return myreturn;
}
#endregion
getsavefilefolderpath( ):获得保存的文件夹的物理路径#region getsavefilefolderpath( ):获得保存的文件夹的物理路径
/**//// <summary>
/// 获得保存的文件夹的物理路径
/// 返回保存的文件夹的物理路径,若为null则表示出错
/// </summary>
/// <param name="format">保存的文件夹路径 或者 格式化方式创建保存文件的文件夹,如按日期"yyyy"+"mm"+"dd":20060511</param>
/// <returns>保存的文件夹的物理路径,若为null则表示出错</returns>
private string getsavefilefolderpath(string format)
{
string mysavefolder = null;
try
{
string folderpath = 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.directoryinfo dir = new system.io.directoryinfo(mysavefolder);
//判断文件夹否存在,不存在则创建
if (!dir.exists)
{
dir.create();
}
}
catch
{
message("获取保存路径出错");
}
return mysavefolder;
}
#endregion
getfileextension( ):获取原文件的扩展名#region getfileextension( ):获取原文件的扩展名
/**//// <summary>
/// 获取原文件的扩展名,返回原文件的扩展名(localfileextension),该函数用到外部变量filetype,即允许的文件扩展名.
/// </summary>
/// <param name="myfilename">原文件名</param>
/// <returns>原文件的扩展名(localfileextension);若返回为null,表明文件无后缀名;若返回为"",则表明扩展名为非法.</returns>
private string getfileextension(string myfilename)
{
string myfileextension = null;
//获得文件扩展名
myfileextension = system.io.path.getextension(myfilename);//若为null,表明文件无后缀名;
//分解允许上传文件的格式
if (myfileextension != "")
{myfileextension = myfileextension.tolower();//转化为小写
}
string[] temp = filetype.split('|');
//设置上传的文件是否是允许的格式
bool flag = false;
//判断上传的文件是否是允许的格式
foreach (string data in temp)
{
if (("." + data) == myfileextension)
{
flag = true;
break;
}
}
if (!flag)
{
myfileextension = "";//不能设置成null,因为null表明文件无后缀名;
}
return myfileextension;
}
#endregion
message( ):弹出消息框#region message( ):弹出消息框
/**//// <summary>
/// 弹出消息框,显示内容(msg),点击"确定"后页面跳转到该路径(url)
/// </summary>
/// <param name="msg">显示内容</param>
/// <param name="url">跳转路径</param>
private void message(string msg, string url)
{
system.web.httpcontext.current.response.write("<script language=javascript>alert('" + msg + "');window.location='" + url + "'</script>");
}
/**//// <summary>
/// 弹出消息框,显示内容(msg),无跳转
/// </summary>
/// <param name="msg">显示内容</param>
private void message(string msg)
{
system.web.httpcontext.current.response.write("<script language=javascript>alert('" + msg + "');</script>");
}
#endregion
}
}
复制代码 代码如下:
<%@ page language="c#" autoeventwireup="true" codefile="upfile.aspx.cs" inherits="inc_upfile" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd";>
<html xmlns="http://www.w3.org/1999/xhtml"; >
<head runat="server">
<title>上传文件</title>
<link href="../manage/style.css" type="text/css" rel=stylesheet />
</head>
<body>
<form id="form1" runat="server">
<div style="left: 0px; clip: rect(0px auto auto 0px); position: absolute; top: 0px">
<asp:fileupload id="fileupload1" runat="server" />
<asp:button id="button1" runat="server" onclick="button1_click" text="上传文件" cssclass="btn2" />
<asp:label id="label1" runat="server" text="label"></asp:label></div>
</form>
</body>
</html>
upfile.aspx.cs
代码
复制代码 代码如下:
using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
public partial class inc_upfile : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
//cut by 梦溪苑。
}
protected void button1_click(object sender, eventargs e)
{
allsheng.upload upfiles = new allsheng.upload();
//httppostedfile file = fileupload1.postedfile;
// allsheng.uploadobj.photosave("/", fileupload1);
httpfilecollection files = httpcontext.current.request.files;
upfiles.path = "../uploadfiles";
string restr= upfiles.saveas(files).tostring();
label1.text = restr;
upfiles = null;
}
}
3、类文件:
代码
复制代码 代码如下:
using system;
using system.data;
using system.configuration;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
/**//// <summary>
/// cls_upfile 的摘要说明
/// </summary>
///
namespace allsheng
{
public class upload
{
变量#region 变量
system.web.httppostedfile postedfile;
protected string localfilename;//原文件名(含扩展名)
protected string localfileextension;//原扩展名
protected long localfilelength;//原文件大小
protected string localfilepath;//原文件路径
protected string savefilename;//保存的文件名(含扩展名)
protected string savefileextension;//保存的扩展名
//protected long savefilelength;//保存的文件大小
protected string savefilepath;//保存文件的服务器端的完整路径
protected string savefilefolderpath;//保存文件的服务器端的文件夹路径
private string path = null;
private string filetype = null;
private int sizes = 0;
#endregion
upload():初始化变量#region upload():初始化变量
/**//// <summary>
/// 初始化变量
/// </summary>
public upload()
{
path = @"uploadimages"; //上传路径
filetype = "jpg|gif|bmp|jpeg|png|rar|doc";
sizes = 200; //传文件的大小,默认200kb
}
#endregion
设置传入的值:path/sizes/filetype#region 设置传入的值:path/sizes/filetype
/**//// <summary>
/// 设置上传路径,如:uploadimages
/// </summary>
public string path
{
set
{
path = @"" + value + @"";
}
}
/**//// <summary>
/// 设置上传文件大小,单位为kb
/// </summary>
public int sizes
{
set
{
sizes = value;
}
}
/**//// <summary>
/// 设置上传文件的类型,如:jpg|gif|bmp
/// </summary>
public string filetype
{
set
{
filetype = value;
}
}
#endregion
saveas()上传文件#region saveas()上传文件
public string saveas(system.web.httpfilecollection files)
{
string myreturn = "";
try
{
for (int ifile = 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(new char[] { '' }) + savefilename + savefileextension;
//以下对文章的内容进行一些加工
system.web.httpcontext.current.response.write("<script>parent.article_content___frame.fck.editordocument.body.innerhtml+='<img src=" + savefilename + savefileextension + " "+" border=0 />'</script>");
}
}
}
catch
{
//异常
message("出现未知错误!");
myreturn = null;
}
return myreturn;
}
#endregion
getsavefilefolderpath( ):获得保存的文件夹的物理路径#region getsavefilefolderpath( ):获得保存的文件夹的物理路径
/**//// <summary>
/// 获得保存的文件夹的物理路径
/// 返回保存的文件夹的物理路径,若为null则表示出错
/// </summary>
/// <param name="format">保存的文件夹路径 或者 格式化方式创建保存文件的文件夹,如按日期"yyyy"+"mm"+"dd":20060511</param>
/// <returns>保存的文件夹的物理路径,若为null则表示出错</returns>
private string getsavefilefolderpath(string format)
{
string mysavefolder = null;
try
{
string folderpath = 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.directoryinfo dir = new system.io.directoryinfo(mysavefolder);
//判断文件夹否存在,不存在则创建
if (!dir.exists)
{
dir.create();
}
}
catch
{
message("获取保存路径出错");
}
return mysavefolder;
}
#endregion
getfileextension( ):获取原文件的扩展名#region getfileextension( ):获取原文件的扩展名
/**//// <summary>
/// 获取原文件的扩展名,返回原文件的扩展名(localfileextension),该函数用到外部变量filetype,即允许的文件扩展名.
/// </summary>
/// <param name="myfilename">原文件名</param>
/// <returns>原文件的扩展名(localfileextension);若返回为null,表明文件无后缀名;若返回为"",则表明扩展名为非法.</returns>
private string getfileextension(string myfilename)
{
string myfileextension = null;
//获得文件扩展名
myfileextension = system.io.path.getextension(myfilename);//若为null,表明文件无后缀名;
//分解允许上传文件的格式
if (myfileextension != "")
{myfileextension = myfileextension.tolower();//转化为小写
}
string[] temp = filetype.split('|');
//设置上传的文件是否是允许的格式
bool flag = false;
//判断上传的文件是否是允许的格式
foreach (string data in temp)
{
if (("." + data) == myfileextension)
{
flag = true;
break;
}
}
if (!flag)
{
myfileextension = "";//不能设置成null,因为null表明文件无后缀名;
}
return myfileextension;
}
#endregion
message( ):弹出消息框#region message( ):弹出消息框
/**//// <summary>
/// 弹出消息框,显示内容(msg),点击"确定"后页面跳转到该路径(url)
/// </summary>
/// <param name="msg">显示内容</param>
/// <param name="url">跳转路径</param>
private void message(string msg, string url)
{
system.web.httpcontext.current.response.write("<script language=javascript>alert('" + msg + "');window.location='" + url + "'</script>");
}
/**//// <summary>
/// 弹出消息框,显示内容(msg),无跳转
/// </summary>
/// <param name="msg">显示内容</param>
private void message(string msg)
{
system.web.httpcontext.current.response.write("<script language=javascript>alert('" + msg + "');</script>");
}
#endregion
}
}
上一篇: Struts2实现文件上传功能实例解析