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('|');elsefileArray[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('|');elsefileArray[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('|');elsefileArray[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('|');elsefileArray[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/";//檔案儲存目錄URLString 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;elsestrFile = 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,可以收穫成果了:
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。