A-A+

asp.net中uploadify文件上传组件的使用

2016年01月07日 前端设计 暂无评论 阅读 5 views 次

本文章来介绍组件uploadify文件上传组件的使用,这里结合了asp.net与uploadify文件上传组件实现文件上传实例,当然uploadify文件上传组件可用于php,jsp,asp,java等。

这个控件有很多参数控制,以及事件的处理响应,相对来说也比较好用。参数控制可以控制上传文件多选、文件类型、文件大小、文件数量、检查文件是否存在,以及一些按钮参数的控制,如文字、高度、宽度等,对提交文件成功与否、完成操作、取消、停止上传等等都有控制,他们的帮助文档也写得比较完善,不过就是各个版本的方法参数完全不同了,但控件是一个好控件。

控件的使用首先要加入必备的脚本类库,由于该控件是利用了Jquery的功能,因此还需要应用Jquery脚本文件,如下所示。

  1. jquery-1.8.0.min.js"   
  2. JQueryTools/uploadify/jquery.uploadify-3.1.min.js  
  3. JQueryTools/uploadify/uploadify.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.   
  12.             $('#file_upload').uploadify({  
  13.                 'swf': 'uploadify.swf',                        //FLash文件路径  
  14.                 'buttonText': '浏  览',                        //按钮文本  
  15.                 'uploader': 'uploadhandler.ashx?guid=' + guid, //处理ASHX页面  
  16.                 'formData' : { 'folder' : 'picture' },         //传参数  
  17.                 'queueID': 'fileQueue',                        //队列的ID  
  18.                 'queueSizeLimit': 10,                           //队列最多可上传文件数量,默认为999  
  19.                 'auto': false,                                 //选择文件后是否自动上传,默认为true  
  20.                 'multi': true,                                 //是否为多选,默认为true  
  21.                 'removeCompleted': true,                       //是否完成后移除序列,默认为true  
  22.                 'fileSizeLimit': '10MB',                       //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值  
  23.                 'fileTypeDesc': 'Image Files',                 //文件描述  
  24.                 'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp',  //上传的文件后缀过滤器  
  25.                 'onQueueComplete': function (event, data) {    //所有队列完成后事件  
  26.                     //ShowUpFiles(guid, type, show_div);  
  27.                     alert("上传完毕!");  
  28.                 },  
  29.                 'onUploadError': function (event, queueId, fileObj, errorObj) {  
  30.                     alert(errorObj.type + ":" + errorObj.info);  
  31.                 }  
  32.             });  
  33.         });  
  34.   
  35.         function newGuid() {  
  36.             var guid = "";  
  37.             for (var i = 1; i <= 32; i++){  
  38.               var n = Math.floor(Math.random()*16.0).toString(16);  
  39.               guid +=   n;  
  40.               if((i==8)||(i==12)||(i==16)||(i==20))  
  41.                 guid += "-";  
  42.             }  
  43.             return guid;  
  44.         }  
  45.     </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.   
  5.     <div>  
  6.     <input type="file" name="file_upload" id="file_upload" />  
  7.         <p>  
  8.             <input type="button" class="shortbutton" id="btnUpload" onclick="javascript:$('#file_upload').uploadify('upload','*')" value="上传" />  
  9.             &nbsp;&nbsp;&nbsp;&nbsp;  
  10.             <input type="button" class="shortbutton" id="btnCancelUpload" onclick="javascript:$('#file_upload').uploadify('cancel')" value="取消" />  
  11.         </p>  
  12.         <div id="div_show_files"></div>  
  13.     </div>  
  14.     </form>  
  15. </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.   
  13.             try  
  14.             {  
  15.                 string guid = context.Request.QueryString["guid"];  
  16.                 string folder = context.Request["folder"];  
  17.                 //LogTextHelper.Info(folder);  
  18.   
  19.                 HttpPostedFile file = context.Request.Files["Filedata"];  
  20.                 if (file != null)  
  21.                 {                      
  22.                     string oldFileName = file.FileName;//原文件名                      
  23.                     int size = file.ContentLength;//附件大小  
  24.                       
  25.                     string extenstion = oldFileName.Substring(oldFileName.LastIndexOf(".") + 1);//后缀名                      
  26.                     string newFileName = GetNewFileName(oldFileName);//生成新文件名  
  27.                     //LogTextHelper.Info(newFileName);  
  28.   
  29.                     #region 上传到远程服务器  
  30.                     //FileServerManage fsw = new FileServerManage();  
  31.                     //string uploadFilePath = "/" + newFileName;  
  32.                     //if (!string.IsNullOrEmpty(folder))  
  33.                     //{  
  34.                     //    uploadFilePath = string.Format("/{0}/{1}", folder, newFileName);  
  35.                     //}  
  36.                     //bool uploaded = fsw.UploadFile(file.InputStream, "/" + folder + "/" + newFileName);   
  37.                     #endregion  
  38.   
  39.                     #region 本地服务器上传  
  40.   
  41.                     AppConfig config = new AppConfig();  
  42.                     string uploadFiles = config.AppConfigGet("uploadFiles");  
  43.                     if (string.IsNullOrEmpty(uploadFiles))  
  44.                     {  
  45.                         uploadFiles = "uploadFiles";  
  46.                     }  
  47.                     if (!string.IsNullOrEmpty(folder))  
  48.                     {  
  49.                         uploadFiles = Path.Combine(uploadFiles, folder);  
  50.                     }  
  51.   
  52.                     string uploadPath = Path.Combine(HttpContext.Current.Server.MapPath("/"), uploadFiles);  
  53.                     if (!Directory.Exists(uploadPath))  
  54.                     {  
  55.                         Directory.CreateDirectory(uploadPath);  
  56.                     }  
  57.                     string newFilePath = Path.Combine(uploadPath, newFileName);  
  58.                     LogTextHelper.Info(newFilePath);  
  59.                     file.SaveAs(newFilePath);  
  60.                     bool uploaded = File.Exists(newFilePath);  
  61.   
  62.                     #endregion  
  63.   
  64.                     if (uploaded)  
  65.                     {  
  66.                         #region 文件保存成功后,写入附件的数据库记录  
  67.                         //AttachmentInfo attachmentInfo = new AttachmentInfo();  
  68.                         //attachmentInfo.EditorTime = DateTime.Now;  
  69.                         //attachmentInfo.FileExtend = extenstion;  
  70.                         //attachmentInfo.FileName = folader + "/" + newFileName;  
  71.                         //attachmentInfo.OldFileName = oldFileName;  
  72.                         //attachmentInfo.Size = size;  
  73.                         //attachmentInfo.Guid = guid;  
  74.                         //BLLFactory<Attachment>.Instance.Insert(attachmentInfo);   
  75.                         #endregion  
  76.                     }  
  77.                 }  
  78.                 else  
  79.                 {  
  80.                     LogTextHelper.Error("上传文件失败");  
  81.                 }  
  82.             }  
  83.             catch (Exception ex)  
  84.             {  
  85.                 LogTextHelper.Error("上传文件失败", ex);  
  86.                 throw;  
  87.             }   
  88.         }  
  89.   
  90.         /// <summary>  
  91.         /// 获取新的名称 比如:aa.jpg转化为aa(20090504).jpg  
  92.         /// </summary>  
  93.         /// <param name="fileName">文件名称[aa.jpg]</param>  
  94.         /// <returns>新的文件名称</returns>  
  95.         public static string GetNewFileName(string fileName)  
  96.         {  
  97.             if (string.IsNullOrEmpty(fileName))  
  98.                 return string.Empty;  
  99.   
  100.             //文件后缀名  
  101.             string extenstion = fileName.Substring(fileName.LastIndexOf(".") + 1);  
  102.             string name = fileName.Substring(0, fileName.LastIndexOf(".")) + "(" + DateTime.Now.ToFileTime() + ")";  
  103.             string newFileName = name + "." + extenstion;  
  104.             return newFileName;  
  105.         }  
  106.   
  107.         public bool IsReusable  
  108.         {  
  109.             get  
  110.             {  
  111.                 return false;  
  112.             }  
  113.         }  
  114.     }  

执行例子的上传操作,我们会提示上传成功的操作,对应的目录下,会有相应的文件写入了。

以上就是这个批量上传文件控件uploadify的使用说明

标签:

给我留言