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下载;

原文地址:https://www.cnblogs.com/felix-wang/p/6943409.html