asp.net(c#)開發中的文件上傳組件uploadify的使用方法(帶進度條)


     上文件傳很常見,現在就文件上傳利用HTML的File控件(uploadify)的,這里為大家介紹一下(uploadify)的一些使用方法。在目前Web開發中用的比較多的,可能uploadify(參考http://www.uploadify.com/)也算一個吧,不過這個版本一直在變化,他們的腳本調用也有很大的不同,甚至調用及參數都一直在變化,很早的時候,那個Flash的按鈕文字還沒法變化,本篇隨筆主要根據項目實際,介紹一下3.1版本的uploadify的控件使用,這版本目前還是最新的,因此對我們做Web開發來說,有一定的參考性。

這個控件有很多參數控制,以及事件的處理響應,相對來說也比較好用。參數控制可以控制上傳文件多選、文件類型、文件大小、文件數量、檢查文件是否存在,以及一些按鈕參數的控制,如文字、高度、寬度等,對提交文件成功與否、完成操作、取消、停止上傳等等都有控制,他們的幫助文檔也寫得比較完善,不過就是各個版本的方法參數完全不同了,但控件是一個好控件。

控件的使用首先要加入必備的腳本類庫,由於該控件是利用了Jquery的功能,因此還需要應用Jquery腳本文件,如下所示。

1  <script src="http://www.jb51.net/JQuery/jquery-1.8.0.min.js" type="text/javascript"></script>
2  <script src="http://www.jb51.net/JQueryTools/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
3  <link href="http://www.jb51.net/JQueryTools/uploadify/uploadify.css" rel="stylesheet" type="text/css" />

配置控件的一些參數,以及相應的處理事件,如下所示。

 1 <script language="javascript" type="text/javascript">
 2         $(function () {
 3             var guid = '<%=Request["guid"] %>';
 4             var type = '<%=Request["type"] %>';
 5             if (guid == null || guid == "") {
 6                 guid = newGuid();
 7             }
 8             if (type != null) {
 9                 type = type + '/';
10             }
11             $('#file_upload').uploadify({
12                 'swf': 'uploadify.swf',                        //FLash文件路徑
13                 'buttonText': '瀏  覽',                        //按鈕文本
14                 'uploader': 'uploadhandler.ashx?guid=' + guid, //處理ASHX頁面
15                 'formData' : { 'folder' : 'picture' },         //傳參數
16                 'queueID': 'fileQueue',                        //隊列的ID
17                 'queueSizeLimit': 10,                           //隊列最多可上傳文件數量,默認為999
18                 'auto': false,                                 //選擇文件后是否自動上傳,默認為true
19                 'multi': true,                                 //是否為多選,默認為true
20                 'removeCompleted': true,                       //是否完成后移除序列,默認為true
21                 'fileSizeLimit': '10MB',                       //單個文件大小,0為無限制,可接受KB,MB,GB等單位的字符串值
22                 'fileTypeDesc': 'Image Files',                 //文件描述
23                 'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp',  //上傳的文件后綴過濾器
24                 'onQueueComplete': function (event, data) {    //所有隊列完成后事件
25                     //ShowUpFiles(guid, type, show_div);
26                     alert("上傳完畢!");
27                 },
28                 'onUploadError': function (event, queueId, fileObj, errorObj) {
29                     alert(errorObj.type + "" + errorObj.info);
30                 }
31             });
32         });
33         function newGuid() {
34             var guid = "";
35             for (var i = 1; i <= 32; i++){
36               var n = Math.floor(Math.random()*16.0).toString(16);
37               guid +=   n;
38               if((i==8)||(i==12)||(i==16)||(i==20))
39                 guid += "-";
40             }
41             return guid;
42         }
43     </script>

再次提一下,這個控件不要參考網上其他的一些說明,否則可能參數及用法不正確,一定要找到對應版本的說明(本篇指的是3.1.1),最好參考該版本的在線文檔。

上面的參數,我基本上都給了注釋了,還有一些不是很重要的參數,這里沒有列出來,需要可以參考在線文檔吧。

值得提到的是,這個版本可以修改Flash里面的文字,非常棒,很討厭以前的那個默認Browse的英文,雖然以前替代圖片可以修改文字,但是還是不太好用。這個直接修改文字,非常好。

值得注意的是uploader參數,這個是我們ashx的后台處理程序,就是控件提交文件給那個頁面進行保存處理,添加數據庫記錄等操作。

頁面代碼使用很簡單,如下所示

 1 <body style="margin-left:10px; margin-top:10px">
 2     <form id="form1" runat="server"  enctype="multipart/form-data">
 3     <div id="fileQueue" class="fileQueue"></div>
 4     <div>
 5     <input type="file" name="file_upload" id="file_upload" />
 6         <p>
 7             <input type="button" class="shortbutton" id="btnUpload" onclick="javascript:$('#file_upload').uploadify('upload','*')" value="上傳" />
 8                 
 9             <input type="button" class="shortbutton" id="btnCancelUpload" onclick="javascript:$('#file_upload').uploadify('cancel')" value="取消" />
10         </p>
11         <div id="div_show_files"></div>
12     </div>
13     </form>
14 </body>

關鍵是后台上傳文件的保存操作了,asp.net一般采用ashx的處理頁面來處理。

  1 /// <summary>
  2     /// 文件上傳后台處理頁面
  3     /// </summary>
  4     [WebService(Namespace = "http://tempuri.org/")]
  5     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  6     public class UploadHandler : IHttpHandler
  7     {
  8         public void ProcessRequest(HttpContext context)
  9         {
 10             context.Response.ContentType = "text/plain";
 11             context.Response.Charset = "utf-8";
 12             try
 13             {
 14                 string guid = context.Request.QueryString["guid"];
 15                 string folder = context.Request["folder"];
 16                 //LogTextHelper.Info(folder);
 17                 HttpPostedFile file = context.Request.Files["Filedata"];
 18                 if (file != null)
 19                 {                    
 20                     string oldFileName = file.FileName;//原文件名                    
 21                     int size = file.ContentLength;//附件大小
 22 
 23                     string extenstion = oldFileName.Substring(oldFileName.LastIndexOf(".") + 1);//后綴名                    
 24                     string newFileName = GetNewFileName(oldFileName);//生成新文件名
 25                     //LogTextHelper.Info(newFileName);
 26                     #region 上傳到遠程服務器
 27                     //FileServerManage fsw = new FileServerManage();
 28                     //string uploadFilePath = "/" + newFileName;
 29                     //if (!string.IsNullOrEmpty(folder))
 30                     //{
 31                     //    uploadFilePath = string.Format("/{0}/{1}", folder, newFileName);
 32                     //}
 33                     //bool uploaded = fsw.UploadFile(file.InputStream, "/" + folder + "/" + newFileName); 
 34                     #endregion
 35                     #region 本地服務器上傳
 36                     AppConfig config = new AppConfig();
 37                     string uploadFiles = config.AppConfigGet("uploadFiles");
 38                     if (string.IsNullOrEmpty(uploadFiles))
 39                     {
 40                         uploadFiles = "uploadFiles";
 41                     }
 42                     if (!string.IsNullOrEmpty(folder))
 43                     {
 44                         uploadFiles = Path.Combine(uploadFiles, folder);
 45                     }
 46                     string uploadPath = Path.Combine(HttpContext.Current.Server.MapPath("/"), uploadFiles);
 47                     if (!Directory.Exists(uploadPath))
 48                     {
 49                         Directory.CreateDirectory(uploadPath);
 50                     }
 51                     string newFilePath = Path.Combine(uploadPath, newFileName);
 52                     LogTextHelper.Info(newFilePath);
 53                     file.SaveAs(newFilePath);
 54                     bool uploaded = File.Exists(newFilePath);
 55                     #endregion
 56                     if (uploaded)
 57                     {
 58                         #region 文件保存成功后,寫入附件的數據庫記錄
 59                         //AttachmentInfo attachmentInfo = new AttachmentInfo();
 60                         //attachmentInfo.EditorTime = DateTime.Now;
 61                         //attachmentInfo.FileExtend = extenstion;
 62                         //attachmentInfo.FileName = folader + "/" + newFileName;
 63                         //attachmentInfo.OldFileName = oldFileName;
 64                         //attachmentInfo.Size = size;
 65                         //attachmentInfo.Guid = guid;
 66                         //BLLFactory<Attachment>.Instance.Insert(attachmentInfo); 
 67                         #endregion
 68                     }
 69                 }
 70                 else
 71                 {
 72                     LogTextHelper.Error("上傳文件失敗");
 73                 }
 74             }
 75             catch (Exception ex)
 76             {
 77                 LogTextHelper.Error("上傳文件失敗", ex);
 78                 throw;
 79             } 
 80         }
 81         /// <summary>
 82         /// 獲取新的名稱 比如:aa.jpg轉化為aa(20090504).jpg
 83         /// </summary>
 84         /// <param name="fileName">文件名稱[aa.jpg]</param>
 85         /// <returns>新的文件名稱</returns>
 86         public static string GetNewFileName(string fileName)
 87         {
 88             if (string.IsNullOrEmpty(fileName))
 89                 return string.Empty;
 90             //文件后綴名
 91             string extenstion = fileName.Substring(fileName.LastIndexOf(".") + 1);
 92             string name = fileName.Substring(0, fileName.LastIndexOf(".")) + "(" + DateTime.Now.ToFileTime() + ")";
 93             string newFileName = name + "." + extenstion;
 94             return newFileName;
 95         }
 96         public bool IsReusable
 97         {
 98             get
 99             {
100                 return false;
101             }
102         }
103     }

 

 

上傳后打開文件夾看到的圖片效果圖

 

 如果你想要比較完整代碼示例,請移步  demo下載;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM