当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET插件uploadify批量上传文件完整使用教程

ASP.NET插件uploadify批量上传文件完整使用教程

2017年12月12日  | 移动技术网IT编程  | 我要评论

中国梦想秀张露,天秤台风,斗牛犬图片

uploadify批量上传文件完整使用教程,供大家参考,具体内容如下

1.首先准备uploadify的js文件,网上一搜一大堆

2.上传页面upfilepage.aspx

关键代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>上传文件</title>
<link href="/jquery.uploadify/uploadify.css" rel="stylesheet" />

<script type="text/javascript" src="/jquery.uploadify/jquery-1.8.3.min.js"></script>
<script src="/jquery.uploadify/swfobject.js" charset="utf-8"></script>
<script src="/jquery.uploadify/jquery.uploadify.v2.1.0.js"></script>
<style type="text/css">
#filesave { padding-left:5px; padding-right:5px;}
#filesave .uploadifyqueueitem{ width:530px;}
#filequeue { padding-left:5px; padding-right:5px;}
#filequeue .uploadifyqueueitem { width:530px;}
#uploadifyuploader { position:absolute; opacity:0;}
.uploadify-button{ height: 30px; line-height: 30px; width: 109px; text-align:center; border:0px; margin-bottom:5px; background:#ff6600; color:#fff;}
.cancel a { background:url(/jquery.uploadify/cancel.png) no-repeat center center; display:inline-block; width:16px; height:16px;}
</style>
</head>
<body>
<form runat="server">
<div>
<div >
<div>
<input type="file" name="uploadify" />
<div><span>添加文件</span></div>
</div>
<div></div>
<div>
<%=getfile() %>
</div>
</div>
</div>
</form>

<script type="text/javascript">
var filecount = 0;
$(document).ready(function () {
filecount = $("#filesave>div.uploadifyqueueitem").length;
$("input[name='radphone']:eq(0)").attr("checked", "checked");
$("#uploadify").uploadify({
'uploader': '/jquery.uploadify/uploadify.swf',//uploadify.swf 文件的相对路径
'script': '/jquery.uploadify/uploadhandler.ashx',//处理文件的程序
//'cancelimg': '/scripts/jquery.uploadify/cancel.png',//取消图片
//'folder': 'upfiles',//上传文件存放的目录
'queueid': 'filequeue',//文件队列的id
//'filedesc': '*.flv;*.mp4;*.wmv;*.avi;*.3gp;*.mpg;*.ppt;*.pptx',//上传格式限制
//'fileext': '*.flv;*.mp4;*.wmv;*.avi;*.3gp;*.mpg;*.ppt;*.pptx',//上传格式限制
"queuesizelimit": "5",//当允许多文件生成时,设置选择文件的个数
'auto': true,//设置为true当选择文件后就直接上传了
'multi': true,//设置为true时可以上传多个文件
"filedataname": "imgfile",//设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据
"sizelimit": "5242880",//上传文件的大小限制,以字节为单位
"simuploadlimit": "1",// 允许同时上传的个数 默认值:1 
"onselect": function (e, queueid, fileobj) {
filecount = $("#filesave>div.uploadifyqueueitem").length;
var less = 5 - filecount;
if (less <= 0) {
layer.msg("最多只能上传5个附件");
$("#a_upload").attr("href", "javascript:");
return false;
} else {
$("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyupload()");
return true;
}
},
"oncomplete": function () {
$.ajax({
type: "post",
url: "/uploadaction/uploadhandler.ashx",
data: { operate: "getfile" },
async: false,
success: function (objdata) {
$("#filesave").html(objdata);
filecount = $("#filesave>div.uploadifyqueueitem").length;
var less = 5 - filecount;
if (less <= 0) {
$("#a_upload").attr("href", "javascript:");
$("#filequeue").html("");
return false;
} else {
$("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyupload()");
return true;
}
}
});
},
"oncancel": function () {
filecount = $("#filesave>div.uploadifyqueueitem").length;
var less = 5 - filecount;
if (less <= 0) {
$("#a_upload").attr("href", "javascript:");
return false;
} else {
$("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyupload()");
return true;
}
},
});
});

function deletefile(path) {
$.ajax({
type: "post",
url: "/uploadaction/uploadhandler.ashx",
data: { operate: "deletefile", file: path },
success: function (objdata) {
$("#filesave").html(objdata);
filecount = $("#filesave>div.uploadifyqueueitem").length;
var less = 5 - filecount;
if (less <= 0) {
$("#a_upload").attr("href", "javascript:");
} else
$("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyupload()");
}
});
}
</script>
</body>
</html>

后台的getfile()方法:

/// <summary>
/// 获取cookie附件信息
/// </summary>
/// <returns></returns>
protected string getfile()
{
#region 获取cookie附件信息

stringbuilder strhtml = new stringbuilder();
httpcookie filecookie = request.cookies["filecookie"];
if (filecookie != null)
{
string[] filearray = new string[1];
if (filecookie.value.contains("|"))
filearray = filecookie.value.split('|');
else
filearray[0] = filecookie.value;
foreach (string objfile in filearray)
{
if (!string.isnullorempty(objfile) && objfile.contains(","))
{
string[] file = objfile.split(',');
strhtml.append(@"<div class='uploadifyqueueitem'>");
strhtml.append(@"<div class='cancel'>");
strhtml.append("<a href='javascript:deletefile(\"" + file[1] + "\")'></a>");
//strhtml.append(@"<img src='/scripts/jquery.uploadify/cancel.png' border='0'>");
strhtml.append(@"</div>");
strhtml.append(@"<span class='filename'>" + httputility.urldecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyprogress'>");
strhtml.append(@"<div class='uploadifyprogressbar' style='width: 100%;'>");
strhtml.append(@"</div>");
strhtml.append(@"</div>");
strhtml.append(@"</div>");
}
}
}
return strhtml.tostring();
#endregion
}

3.uploadaction文件夹下的一般处理程序:

public void processrequest(httpcontext context)
{
context.response.contenttype = "text/plain";
string operate = context.request["operate"];
if (operate == "deletefile")
{
#region 删除文件附件信息
//获取文件路径
string filepath = context.server.mappath(context.request["file"]);
//判断文件是否存在
if (file.exists(filepath))
file.delete(filepath);//删除文件
//获取附件cookie信息
httpcookie filecookie = context.request.cookies["filecookie"];
string[] filearray = new string[1];
if (filecookie != null)
{
filepath = filepath.remove(0, filepath.indexof("upfiles")).replace("\\", "/");
if (filecookie.value.contains("|"))
filearray = filecookie.value.split('|');
else
filearray[0] = filecookie.value;
string strfile = "";
for (int i = 0; i < filearray.length; i++)
{
if (!filearray[i].contains(filepath))
strfile += filearray[i] + "|";
}
if (strfile.contains("|"))
strfile = strfile.remove(strfile.length - 1);
filecookie.value = strfile;
filecookie.expires = datetime.now.adddays(1);
filecookie.httponly = true;
context.response.appendcookie(filecookie);


stringbuilder strhtml = new stringbuilder();
if (filecookie.value.contains("|"))
filearray = filecookie.value.split('|');
else
filearray[0] = filecookie.value;
foreach (string objfile in filearray)
{
if (!string.isnullorempty(objfile) && objfile.contains(","))
{
string[] file = objfile.split(',');
strhtml.append(@"<div class='uploadifyqueueitem'>");
strhtml.append(@"<div class='cancel'>");
strhtml.append("<a href='javascript:deletefile(\"" + file[1] + "\")'></a>");
//strhtml.append(@"<img src='/scripts/jquery.uploadify-v2.1.0/cancel.png' border='0'>");
strhtml.append(@"</div>");
strhtml.append(@"<span class='filename'>" + httputility.urldecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyprogress'>");
strhtml.append(@"<div class='uploadifyprogressbar' style='width: 100%;'>");
strhtml.append(@"</div>");
strhtml.append(@"</div>");
strhtml.append(@"</div>");
}
}
context.response.write(strhtml.tostring());
}
#endregion
}
else if (operate == "getfile")
{
#region 获取上传的附件并展示
stringbuilder strhtml = new stringbuilder();
httpcookie filecookie = context.request.cookies["filecookie"];
if (filecookie != null)
{
string[] filearray = new string[1];
if (filecookie.value.contains("|"))
filearray = filecookie.value.split('|');
else
filearray[0] = filecookie.value;
foreach (string objfile in filearray)
{
if (!string.isnullorempty(objfile) && objfile.contains(","))
{
string[] file = objfile.split(',');
strhtml.append(@"<div class='uploadifyqueueitem'>");
strhtml.append(@"<div class='cancel'>");
strhtml.append("<a href='javascript:deletefile(\"" + file[1] + "\")'>");
//strhtml.append(@"<img src='/scripts/jquery.uploadify-v2.1.0/cancel.png' border='0'></a>");
strhtml.append(@"</div>");
strhtml.append(@"<span class='filename'>" + httputility.urldecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyprogress'>");
strhtml.append(@"<div class='uploadifyprogressbar' style='width: 100%;'>");
strhtml.append(@"</div>");
strhtml.append(@"</div>");
strhtml.append(@"</div>");
}
}
}
context.response.write(strhtml.tostring());
#endregion
}
}

4.上传文件uploadhandler.ashx一般处理程序代码,文件上传路径可以根据剧情需要自由设定:

public void processrequest(httpcontext context)
{
context.response.contenttype = "text/plain";

httpcookie filecookie = context.request.cookies["filecookie"];
if (filecookie != null)
{
string[] filearray = new string[1];
if (filecookie.value.contains("|"))
filearray = filecookie.value.split('|');
if (filearray.length >= 5)
return;
}
else
{
filecookie = new httpcookie("filecookie");
filecookie.value = "";
context.response.cookies.add(filecookie);
}

string aspxurl = context.request.path.substring(0, context.request.path.lastindexof("/") + 1);

//文件保存目录路径
string savepath = "/upfiles/";

//文件保存目录url
string saveurl = "/upfiles/";

//if (context.request.cookies["member"] != null)
//{
// savepath += context.request.cookies["member"]["memberid"] + "/";
// saveurl += context.request.cookies["member"]["memberid"] + "/";
//}
string member = guid.newguid().tostring().trim().replace("-", "");
savepath += member + "/";
saveurl += member + "/";

//定义允许上传的文件扩展名
/*hashtable exttable = new hashtable();
exttable.add("image", "gif,jpg,jpeg,png,bmp");
exttable.add("flash", "swf,flv");
exttable.add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
exttable.add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4,wps");*/

//最大文件大小
int maxsize = 5242880;

httppostedfile imgfile = context.request.files["imgfile"];
/*if (imgfile == null)
{
showerror("请选择文件。");
}*/

string dirpath = context.server.mappath(savepath);
if (!directory.exists(dirpath))
{
directory.createdirectory(dirpath);
//showerror("上传目录不存在。");
}

string dirname = context.request.querystring["dir"];
if (string.isnullorempty(dirname))
{
dirname = "file";
}
/*if (!exttable.containskey(dirname))
{
showerror("目录名不正确。");
}*/

string filename = imgfile.filename;
string fileext = path.getextension(filename).tolower();


/*if (string.isnullorempty(fileext) || array.indexof(((string)exttable[dirname]).split(','), fileext.substring(1).tolower()) == -1)
{
showerror("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)exttable[dirname]) + "格式。");
}
if (dirname.contains("image"))
{
if (imgfile.inputstream == null || imgfile.inputstream.length > maxsize)
{
showerror("上传文件超过5m大小限制。");
}
}*/

//创建文件夹
dirpath += dirname + "/";
saveurl += dirname + "/";
if (!directory.exists(dirpath))
{
directory.createdirectory(dirpath);
}
string ymd = datetime.now.tostring("yyyymmdd", datetimeformatinfo.invariantinfo);
dirpath += ymd + "/";
saveurl += ymd + "/";
if (!directory.exists(dirpath))
{
directory.createdirectory(dirpath);
}

string newfilename = datetime.now.tostring("yyyymmddhhmmss_ffff", datetimeformatinfo.invariantinfo) + fileext;
string filepath = dirpath + newfilename;

imgfile.saveas(filepath);

string fileurl = saveurl + newfilename;

/*hashtable hash = new hashtable();
hash["error"] = 0;
hash["url"] = fileurl;
context.response.addheader("content-type", "text/html; charset=utf-8");
context.response.write(jsonmapper.tojson(hash));
context.response.end();*/

if (filecookie != null)
{
string strfile = filecookie.value;
if (!string.isnullorempty(strfile))
strfile = strfile + "|" + httputility.urlencode(filename) + "," + fileurl;
else
strfile = httputility.urlencode(filename) + "," + fileurl;
filecookie.value = strfile;
filecookie.expires = datetime.now.adddays(1);
filecookie.httponly = true;
context.response.appendcookie(filecookie);
}
context.response.write("1");
context.response.end();
}

5.所有代码敲完ok,可以收获成果了:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网