ASP.NET插件uploadify批量上传文件完整使用教程
更新时间:2021年9月22日 10:07 点击:1866
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,可以收获成果了:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。
相关文章
- 这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
- 在开发过程中,使用Visual Studio的断点调试功能可以很方便帮我们调试发现程序存在的错误,同样Visual Studio也支持对SQL Server里面的存储过程进行调试,下面就让我们看看具体的调试方法。...2021-09-22
php无刷新利用iframe实现页面无刷新上传文件(1/2)
利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25- 分享给大家php判断上传文件类型的方法,大家一起学习学习。/** * 读取文件前几个字节 判断文件类型 * @return String */ function checkTitle($filename){ $file=fopen($filename, "rb"); $bin=fread($file, 2); /...2015-10-21
ASP.NET Core根据环境变量支持多个 appsettings.json配置文件
这篇文章主要介绍了ASP.NET Core根据环境变量支持多个 appsettings.json配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22- 这篇文章主要介绍了记一次EFCore类型转换错误及解决方案,帮助大家更好的理解和学习使用asp.net core,感兴趣的朋友可以了解下...2021-09-22
详解ASP.NET Core 中基于工厂的中间件激活的实现方法
这篇文章主要介绍了ASP.NET Core 中基于工厂的中间件激活的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22asp.net通过消息队列处理高并发请求(以抢小米手机为例)
这篇文章主要介绍了asp.net通过消息队列处理高并发请求(以抢小米手机为例),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22- 这篇文章主要介绍了Vue使用formData格式类型上传文件的示例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
ASP.NET单选按钮控件RadioButton常用属性和方法介绍
RadioButton又称单选按钮,其在工具箱中的图标为 ,单选按钮通常成组出现,用于提供两个或多个互斥选项,即在一组单选钮中只能选择一个...2021-09-22ASP.NET 2.0中的数据操作:使用两个DropDownList过滤的主/从报表
在前面的指南中我们研究了如何显示一个简单的主/从报表, 该报表使用DropDownList和GridView控件, DropDownList填充类别,GridView显示选定类别的产品. 这类报表用于显示具有...2016-05-19ASP.NET中iframe框架点击左边页面链接 右边显示链接页面内容
这篇文章主要介绍了ASP.NET中iframe框架点击左边页面链接,右边显示链接页面内容的实现代码,感兴趣的小伙伴们可以参考一下...2021-09-22- ASP.NET Web API具有与ASP.NET MVC类似的编程方式,ASP.NET Web API不仅仅具有一个完全独立的消息处理管道,而且这个管道比为ASP.NET MVC设计的管道更为复杂,功能也更为强大。下面创建一个简单的Web API项目,需要的朋友可以参考下...2021-09-22
- 下面小编就为大家分享一篇c# FTP上传文件的实例代码,超简单哦~希望对大家有所帮助。一起跟随小编过来看看吧,...2020-06-25
- 这篇文章主要介绍了ASP.NET连接MySql数据库的2个方法及示例,使用的是MySQL官方组件和ODBC.NET,需要的朋友可以参考下...2021-09-22
- 这篇文章主要介绍了Asp.Net使用Bulk实现批量插入数据的方法,对于进行asp.net数据库程序设计非常有借鉴价值,需要的朋友可以参考下...2021-09-22
在ASP.NET 2.0中操作数据之二十九:用DataList和Repeater来显示数据
本文主要讲解ASP.NET 2.0中如何使用DataList 和 Repeater 来呈现数据,DataList包含一个table标记,而Repeater不会添加任何额外的代码,个人在实际开发中更推荐使用Repeater。...2021-09-22- 这篇文章主要介绍了获取DataTable选择第一行某一列值,需要的朋友可以参考下...2021-09-22
- 这篇文章主要介绍了ASP.Net中的async+await异步编程的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
- 这篇文章介绍了Asp.net动态生成html页面的方法,有需要的朋友可以参考一下...2021-09-22