当前位置:Gxlcms > asp.net > ASP.NET插件uploadify批量上传文件完整使用教程

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

时间:2021-07-01 10:21:17 帮助过:13人阅读

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

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

2.上传页面UpFilePage.aspx

关键代码:

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  4. <title>上传文件</title>
  5. <link href="/jquery.uploadify/uploadify.css" rel="stylesheet" />
  6. <script type="text/javascript" src="/jquery.uploadify/jquery-1.8.3.min.js"></script>
  7. <script src="/jquery.uploadify/swfobject.js" charset="utf-8"></script>
  8. <script src="/jquery.uploadify/jquery.uploadify.v2.1.0.js"></script>
  9. <style type="text/css">
  10. #fileSave { padding-left:5px; padding-right:5px;}
  11. #fileSave .uploadifyQueueItem{ width:530px;}
  12. #fileQueue { padding-left:5px; padding-right:5px;}
  13. #fileQueue .uploadifyQueueItem { width:530px;}
  14. #uploadifyUploader { position:absolute; opacity:0;}
  15. .uploadify-button{ height: 30px; line-height: 30px; width: 109px; text-align:center; border:0px; margin-bottom:5px; background:#ff6600; color:#fff;}
  16. .cancel a { background:url(/jquery.uploadify/cancel.png) no-repeat center center; display:inline-block; width:16px; height:16px;}
  17. </style>
  18. </head>
  19. <body>
  20. <form runat="server">
  21. <div>
  22. <div >
  23. <div>
  24. <input type="file" name="uploadify" />
  25. <div><span>添加文件</span></div>
  26. </div>
  27. <div></div>
  28. <div>
  29. <%=GetFile() %>
  30. </div>
  31. </div>
  32. </div>
  33. </form>
  34. <script type="text/javascript">
  35. var fileCount = 0;
  36. $(document).ready(function () {
  37. fileCount = $("#fileSave>div.uploadifyQueueItem").length;
  38. $("input[name='radPhone']:eq(0)").attr("checked", "checked");
  39. $("#uploadify").uploadify({
  40. 'uploader': '/jquery.uploadify/uploadify.swf',//uploadify.swf 文件的相对路径
  41. 'script': '/jquery.uploadify/uploadHandler.ashx',//处理文件的程序
  42. //'cancelImg': '/Scripts/jquery.uploadify/cancel.png',//取消图片
  43. //'folder': 'upfiles',//上传文件存放的目录
  44. 'queueID': 'fileQueue',//文件队列的ID
  45. //'fileDesc': '*.flv;*.mp4;*.wmv;*.avi;*.3gp;*.mpg;*.ppt;*.pptx',//上传格式限制
  46. //'fileExt': '*.flv;*.mp4;*.wmv;*.avi;*.3gp;*.mpg;*.ppt;*.pptx',//上传格式限制
  47. "queueSizeLimit": "5",//当允许多文件生成时,设置选择文件的个数
  48. 'auto': true,//设置为true当选择文件后就直接上传了
  49. 'multi': true,//设置为true时可以上传多个文件
  50. "fileDataName": "imgFile",//设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据
  51. "sizeLimit": "5242880",//上传文件的大小限制,以字节为单位
  52. "simUploadLimit": "1",// 允许同时上传的个数 默认值:1
  53. "onSelect": function (e, queueId, fileObj) {
  54. fileCount = $("#fileSave>div.uploadifyQueueItem").length;
  55. var less = 5 - fileCount;
  56. if (less <= 0) {
  57. layer.msg("最多只能上传5个附件");
  58. $("#a_upload").attr("href", "javascript:");
  59. return false;
  60. } else {
  61. $("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyUpload()");
  62. return true;
  63. }
  64. },
  65. "onComplete": function () {
  66. $.ajax({
  67. type: "post",
  68. url: "/UploadAction/UploadHandler.ashx",
  69. data: { operate: "GetFile" },
  70. async: false,
  71. success: function (objdata) {
  72. $("#fileSave").html(objdata);
  73. fileCount = $("#fileSave>div.uploadifyQueueItem").length;
  74. var less = 5 - fileCount;
  75. if (less <= 0) {
  76. $("#a_upload").attr("href", "javascript:");
  77. $("#fileQueue").html("");
  78. return false;
  79. } else {
  80. $("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyUpload()");
  81. return true;
  82. }
  83. }
  84. });
  85. },
  86. "onCancel": function () {
  87. fileCount = $("#fileSave>div.uploadifyQueueItem").length;
  88. var less = 5 - fileCount;
  89. if (less <= 0) {
  90. $("#a_upload").attr("href", "javascript:");
  91. return false;
  92. } else {
  93. $("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyUpload()");
  94. return true;
  95. }
  96. },
  97. });
  98. });
  99. function deleteFile(path) {
  100. $.ajax({
  101. type: "post",
  102. url: "/UploadAction/UploadHandler.ashx",
  103. data: { operate: "deleteFile", file: path },
  104. success: function (objdata) {
  105. $("#fileSave").html(objdata);
  106. fileCount = $("#fileSave>div.uploadifyQueueItem").length;
  107. var less = 5 - fileCount;
  108. if (less <= 0) {
  109. $("#a_upload").attr("href", "javascript:");
  110. } else
  111. $("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyUpload()");
  112. }
  113. });
  114. }
  115. </script>
  116. </body>
  117. </html>

后台的GetFile()方法:

  1. /// <summary>
  2. /// 获取cookie附件信息
  3. /// </summary>
  4. /// <returns></returns>
  5. protected string GetFile()
  6. {
  7. #region 获取cookie附件信息
  8. StringBuilder strHtml = new StringBuilder();
  9. HttpCookie fileCookie = Request.Cookies["FileCookie"];
  10. if (fileCookie != null)
  11. {
  12. string[] fileArray = new string[1];
  13. if (fileCookie.Value.Contains("|"))
  14. fileArray = fileCookie.Value.Split('|');
  15. else
  16. fileArray[0] = fileCookie.Value;
  17. foreach (string objFile in fileArray)
  18. {
  19. if (!string.IsNullOrEmpty(objFile) && objFile.Contains(","))
  20. {
  21. string[] file = objFile.Split(',');
  22. strHtml.Append(@"<div class='uploadifyQueueItem'>");
  23. strHtml.Append(@"<div class='cancel'>");
  24. strHtml.Append("<a href='javascript:deleteFile(\"" + file[1] + "\")'></a>");
  25. //strHtml.Append(@"<img src='/Scripts/jquery.uploadify/cancel.png' border='0'>");
  26. strHtml.Append(@"</div>");
  27. strHtml.Append(@"<span class='fileName'>" + HttpUtility.UrlDecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyProgress'>");
  28. strHtml.Append(@"<div class='uploadifyProgressBar' style='width: 100%;'>");
  29. strHtml.Append(@"</div>");
  30. strHtml.Append(@"</div>");
  31. strHtml.Append(@"</div>");
  32. }
  33. }
  34. }
  35. return strHtml.ToString();
  36. #endregion
  37. }

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

  1. public void ProcessRequest(HttpContext context)
  2. {
  3. context.Response.ContentType = "text/plain";
  4. string operate = context.Request["operate"];
  5. if (operate == "deleteFile")
  6. {
  7. #region 删除文件附件信息
  8. //获取文件路径
  9. string filePath = context.Server.MapPath(context.Request["file"]);
  10. //判断文件是否存在
  11. if (File.Exists(filePath))
  12. File.Delete(filePath);//删除文件
  13. //获取附件cookie信息
  14. HttpCookie fileCookie = context.Request.Cookies["FileCookie"];
  15. string[] fileArray = new string[1];
  16. if (fileCookie != null)
  17. {
  18. filePath = filePath.Remove(0, filePath.IndexOf("upfiles")).Replace("\\", "/");
  19. if (fileCookie.Value.Contains("|"))
  20. fileArray = fileCookie.Value.Split('|');
  21. else
  22. fileArray[0] = fileCookie.Value;
  23. string strFile = "";
  24. for (int i = 0; i < fileArray.Length; i++)
  25. {
  26. if (!fileArray[i].Contains(filePath))
  27. strFile += fileArray[i] + "|";
  28. }
  29. if (strFile.Contains("|"))
  30. strFile = strFile.Remove(strFile.Length - 1);
  31. fileCookie.Value = strFile;
  32. fileCookie.Expires = DateTime.Now.AddDays(1);
  33. fileCookie.HttpOnly = true;
  34. context.Response.AppendCookie(fileCookie);
  35. StringBuilder strHtml = new StringBuilder();
  36. if (fileCookie.Value.Contains("|"))
  37. fileArray = fileCookie.Value.Split('|');
  38. else
  39. fileArray[0] = fileCookie.Value;
  40. foreach (string objFile in fileArray)
  41. {
  42. if (!string.IsNullOrEmpty(objFile) && objFile.Contains(","))
  43. {
  44. string[] file = objFile.Split(',');
  45. strHtml.Append(@"<div class='uploadifyQueueItem'>");
  46. strHtml.Append(@"<div class='cancel'>");
  47. strHtml.Append("<a href='javascript:deleteFile(\"" + file[1] + "\")'></a>");
  48. //strHtml.Append(@"<img src='/Scripts/jquery.uploadify-v2.1.0/cancel.png' border='0'>");
  49. strHtml.Append(@"</div>");
  50. strHtml.Append(@"<span class='fileName'>" + HttpUtility.UrlDecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyProgress'>");
  51. strHtml.Append(@"<div class='uploadifyProgressBar' style='width: 100%;'>");
  52. strHtml.Append(@"</div>");
  53. strHtml.Append(@"</div>");
  54. strHtml.Append(@"</div>");
  55. }
  56. }
  57. context.Response.Write(strHtml.ToString());
  58. }
  59. #endregion
  60. }
  61. else if (operate == "GetFile")
  62. {
  63. #region 获取上传的附件并展示
  64. StringBuilder strHtml = new StringBuilder();
  65. HttpCookie fileCookie = context.Request.Cookies["FileCookie"];
  66. if (fileCookie != null)
  67. {
  68. string[] fileArray = new string[1];
  69. if (fileCookie.Value.Contains("|"))
  70. fileArray = fileCookie.Value.Split('|');
  71. else
  72. fileArray[0] = fileCookie.Value;
  73. foreach (string objFile in fileArray)
  74. {
  75. if (!string.IsNullOrEmpty(objFile) && objFile.Contains(","))
  76. {
  77. string[] file = objFile.Split(',');
  78. strHtml.Append(@"<div class='uploadifyQueueItem'>");
  79. strHtml.Append(@"<div class='cancel'>");
  80. strHtml.Append("<a href='javascript:deleteFile(\"" + file[1] + "\")'>");
  81. //strHtml.Append(@"<img src='/Scripts/jquery.uploadify-v2.1.0/cancel.png' border='0'></a>");
  82. strHtml.Append(@"</div>");
  83. strHtml.Append(@"<span class='fileName'>" + HttpUtility.UrlDecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyProgress'>");
  84. strHtml.Append(@"<div class='uploadifyProgressBar' style='width: 100%;'>");
  85. strHtml.Append(@"</div>");
  86. strHtml.Append(@"</div>");
  87. strHtml.Append(@"</div>");
  88. }
  89. }
  90. }
  91. context.Response.Write(strHtml.ToString());
  92. #endregion
  93. }
  94. }

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

  1. public void ProcessRequest(HttpContext context)
  2. {
  3. context.Response.ContentType = "text/plain";
  4. HttpCookie fileCookie = context.Request.Cookies["FileCookie"];
  5. if (fileCookie != null)
  6. {
  7. string[] fileArray = new string[1];
  8. if (fileCookie.Value.Contains("|"))
  9. fileArray = fileCookie.Value.Split('|');
  10. if (fileArray.Length >= 5)
  11. return;
  12. }
  13. else
  14. {
  15. fileCookie = new HttpCookie("FileCookie");
  16. fileCookie.Value = "";
  17. context.Response.Cookies.Add(fileCookie);
  18. }
  19. String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);
  20. //文件保存目录路径
  21. String savePath = "/upfiles/";
  22. //文件保存目录URL
  23. String saveUrl = "/upfiles/";
  24. //if (context.Request.Cookies["Member"] != null)
  25. //{
  26. // savePath += context.Request.Cookies["Member"]["MemberId"] + "/";
  27. // saveUrl += context.Request.Cookies["Member"]["MemberId"] + "/";
  28. //}
  29. string Member = Guid.NewGuid().ToString().Trim().Replace("-", "");
  30. savePath += Member + "/";
  31. saveUrl += Member + "/";
  32. //定义允许上传的文件扩展名
  33. /*Hashtable extTable = new Hashtable();
  34. extTable.Add("image", "gif,jpg,jpeg,png,bmp");
  35. extTable.Add("flash", "swf,flv");
  36. extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
  37. 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");*/
  38. //最大文件大小
  39. int maxSize = 5242880;
  40. HttpPostedFile imgFile = context.Request.Files["imgFile"];
  41. /*if (imgFile == null)
  42. {
  43. showError("请选择文件。");
  44. }*/
  45. String dirPath = context.Server.MapPath(savePath);
  46. if (!Directory.Exists(dirPath))
  47. {
  48. Directory.CreateDirectory(dirPath);
  49. //showError("上传目录不存在。");
  50. }
  51. String dirName = context.Request.QueryString["dir"];
  52. if (String.IsNullOrEmpty(dirName))
  53. {
  54. dirName = "file";
  55. }
  56. /*if (!extTable.ContainsKey(dirName))
  57. {
  58. showError("目录名不正确。");
  59. }*/
  60. String fileName = imgFile.FileName;
  61. String fileExt = Path.GetExtension(fileName).ToLower();
  62. /*if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
  63. {
  64. showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
  65. }
  66. if (dirName.Contains("image"))
  67. {
  68. if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
  69. {
  70. showError("上传文件超过5M大小限制。");
  71. }
  72. }*/
  73. //创建文件夹
  74. dirPath += dirName + "/";
  75. saveUrl += dirName + "/";
  76. if (!Directory.Exists(dirPath))
  77. {
  78. Directory.CreateDirectory(dirPath);
  79. }
  80. String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
  81. dirPath += ymd + "/";
  82. saveUrl += ymd + "/";
  83. if (!Directory.Exists(dirPath))
  84. {
  85. Directory.CreateDirectory(dirPath);
  86. }
  87. String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
  88. String filePath = dirPath + newFileName;
  89. imgFile.SaveAs(filePath);
  90. String fileUrl = saveUrl + newFileName;
  91. /*Hashtable hash = new Hashtable();
  92. hash["error"] = 0;
  93. hash["url"] = fileUrl;
  94. context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
  95. context.Response.Write(JsonMapper.ToJson(hash));
  96. context.Response.End();*/
  97. if (fileCookie != null)
  98. {
  99. string strFile = fileCookie.Value;
  100. if (!string.IsNullOrEmpty(strFile))
  101. strFile = strFile + "|" + HttpUtility.UrlEncode(fileName) + "," + fileUrl;
  102. else
  103. strFile = HttpUtility.UrlEncode(fileName) + "," + fileUrl;
  104. fileCookie.Value = strFile;
  105. fileCookie.Expires = DateTime.Now.AddDays(1);
  106. fileCookie.HttpOnly = true;
  107. context.Response.AppendCookie(fileCookie);
  108. }
  109. context.Response.Write("1");
  110. context.Response.End();
  111. }

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

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

人气教程排行