在Web開發中,有很多可以上傳的組件模塊,利用HTML的File控件的上傳也是一種辦法,不過這種方式,需要處理的細節比較多,而且只能支持單文件的操作。在目前Web開發中用的比較多的,可能uploadify(參考http://www.uploadify.com/)也算一個吧,不過這個版本一直在變化,他們的腳本調用也有很大的不同,甚至調用及參數都一直在變化,很早的時候,那個Flash的按鈕文字還沒法變化,本篇隨筆主要根據項目實際,介紹一下3.1版本的uploadify的控件使用,這版本目前還是最新的,因此對我們做Web開發來說,有一定的參考性。
這個控件有很多參數控制,以及事件的處理響應,相對來說也比較好用。參數控制可以控制上傳文件多選、文件類型、文件大小、文件數量、檢查文件是否存在,以及一些按鈕參數的控制,如文字、高度、寬度等,對提交文件成功與否、完成操作、取消、停止上傳等等都有控制,他們的幫助文檔也寫得比較完善,不過就是各個版本的方法參數完全不同了,但控件是一個好控件。
控件的使用首先要加入必備的腳本類庫,由於該控件是利用了Jquery的功能,因此還需要應用Jquery腳本文件,如下所示。
<script src="http://www.cnblogs.com/JQuery/jquery-1.8.0.min.js" type="text/javascript"></script> <script src="http://www.cnblogs.com/JQueryTools/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script> <link href="http://www.cnblogs.com/JQueryTools/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
配置控件的一些參數,以及相應的處理事件,如下所示。
<script language="javascript" type="text/javascript"> $(function () { var guid = '<%=Request["guid"] %>'; var type = '<%=Request["type"] %>'; if (guid == null || guid == "") { guid = newGuid(); } if (type != null) { type = type + '/'; } $('#file_upload').uploadify({ 'swf': 'uploadify.swf', //FLash文件路徑 'buttonText': '瀏 覽', //按鈕文本 'uploader': 'uploadhandler.ashx?guid=' + guid, //處理ASHX頁面 'formData' : { 'folder' : 'picture' }, //傳參數 'queueID': 'fileQueue', //隊列的ID 'queueSizeLimit': 10, //隊列最多可上傳文件數量,默認為999 'auto': false, //選擇文件后是否自動上傳,默認為true 'multi': true, //是否為多選,默認為true 'removeCompleted': true, //是否完成后移除序列,默認為true 'fileSizeLimit': '10MB', //單個文件大小,0為無限制,可接受KB,MB,GB等單位的字符串值 'fileTypeDesc': 'Image Files', //文件描述 'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp', //上傳的文件后綴過濾器 'onQueueComplete': function (event, data) { //所有隊列完成后事件 //ShowUpFiles(guid, type, show_div); alert("上傳完畢!"); }, 'onUploadError': function (event, queueId, fileObj, errorObj) { alert(errorObj.type + ":" + errorObj.info); } }); }); function newGuid() { var guid = ""; for (var i = 1; i <= 32; i++){ var n = Math.floor(Math.random()*16.0).toString(16); guid += n; if((i==8)||(i==12)||(i==16)||(i==20)) guid += "-"; } return guid; } </script>
再次提一下,這個控件不要參考網上其他的一些說明,否則可能參數及用法不正確,一定要找到對應版本的說明(本篇指的是3.1.1),最好參考該版本的在線文檔。
上面的參數,我基本上都給了注釋了,還有一些不是很重要的參數,這里沒有列出來,需要可以參考在線文檔吧。
值得提到的是,這個版本可以修改Flash里面的文字,非常棒,很討厭以前的那個默認Browse的英文,雖然以前替代圖片可以修改文字,但是還是不太好用。這個直接修改文字,非常好。
值得注意的是uploader參數,這個是我們ashx的后台處理程序,就是控件提交文件給那個頁面進行保存處理,添加數據庫記錄等操作。

頁面代碼使用很簡單,如下所示
<body style="margin-left:10px; margin-top:10px"> <form id="form1" runat="server" enctype="multipart/form-data"> <div id="fileQueue" class="fileQueue"></div> <div> <input type="file" name="file_upload" id="file_upload" /> <p> <input type="button" class="shortbutton" id="btnUpload" onclick="javascript:$('#file_upload').uploadify('upload','*')" value="上傳" /> <input type="button" class="shortbutton" id="btnCancelUpload" onclick="javascript:$('#file_upload').uploadify('cancel')" value="取消" /> </p> <div id="div_show_files"></div> </div> </form> </body>
關鍵是后台上傳文件的保存操作了,asp.net一般采用ashx的處理頁面來處理。
/// <summary> /// 文件上傳后台處理頁面 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class UploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; try { string guid = context.Request.QueryString["guid"]; string folder = context.Request["folder"]; //LogTextHelper.Info(folder); HttpPostedFile file = context.Request.Files["Filedata"]; if (file != null) { string oldFileName = file.FileName;//原文件名 int size = file.ContentLength;//附件大小 string extenstion = oldFileName.Substring(oldFileName.LastIndexOf(".") + 1);//后綴名 string newFileName = GetNewFileName(oldFileName);//生成新文件名 //LogTextHelper.Info(newFileName); #region 上傳到遠程服務器 //FileServerManage fsw = new FileServerManage(); //string uploadFilePath = "/" + newFileName; //if (!string.IsNullOrEmpty(folder)) //{ // uploadFilePath = string.Format("/{0}/{1}", folder, newFileName); //} //bool uploaded = fsw.UploadFile(file.InputStream, "/" + folder + "/" + newFileName); #endregion #region 本地服務器上傳 AppConfig config = new AppConfig(); string uploadFiles = config.AppConfigGet("uploadFiles"); if (string.IsNullOrEmpty(uploadFiles)) { uploadFiles = "uploadFiles"; } if (!string.IsNullOrEmpty(folder)) { uploadFiles = Path.Combine(uploadFiles, folder); } string uploadPath = Path.Combine(HttpContext.Current.Server.MapPath("/"), uploadFiles); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string newFilePath = Path.Combine(uploadPath, newFileName); LogTextHelper.Info(newFilePath); file.SaveAs(newFilePath); bool uploaded = File.Exists(newFilePath); #endregion if (uploaded) { #region 文件保存成功后,寫入附件的數據庫記錄 //AttachmentInfo attachmentInfo = new AttachmentInfo(); //attachmentInfo.EditorTime = DateTime.Now; //attachmentInfo.FileExtend = extenstion; //attachmentInfo.FileName = folader + "/" + newFileName; //attachmentInfo.OldFileName = oldFileName; //attachmentInfo.Size = size; //attachmentInfo.Guid = guid; //BLLFactory<Attachment>.Instance.Insert(attachmentInfo); #endregion } } else { LogTextHelper.Error("上傳文件失敗"); } } catch (Exception ex) { LogTextHelper.Error("上傳文件失敗", ex); throw; } } /// <summary> /// 獲取新的名稱 比如:aa.jpg轉化為aa(20090504).jpg /// </summary> /// <param name="fileName">文件名稱[aa.jpg]</param> /// <returns>新的文件名稱</returns> public static string GetNewFileName(string fileName) { if (string.IsNullOrEmpty(fileName)) return string.Empty; //文件后綴名 string extenstion = fileName.Substring(fileName.LastIndexOf(".") + 1); string name = fileName.Substring(0, fileName.LastIndexOf(".")) + "(" + DateTime.Now.ToFileTime() + ")"; string newFileName = name + "." + extenstion; return newFileName; } public bool IsReusable { get { return false; } } }

執行例子的上傳操作,我們會提示上傳成功的操作,對應的目錄下,會有相應的文件寫入了。

以上就是這個批量上傳文件控件uploadify的使用說明,供大家學習參考。
