码迷,mamicode.com
首页 > Web开发 > 详细

JQuery Uplodify上传附件(同一个页面多个uplodify控件解决方案)

时间:2016-02-22 12:05:20      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:

功能描述:实现同一页面中多个不同附件的上传保存,且做到最大程度的减少代码修改量(最大程度的公用),为了方便实现垃圾数据和垃圾文件的处理,项目采用临时文件夹的方式:即:文件自动上传先保存到临时文件夹下,在保存数据之后移动文件到正式目录,页面上对附件的所有操作只有用户点击“保存”后起效。插件名称及版本:Uploadify v3.1.1。

解决方案:

1.引用(页面开头):

    <link href="~/Scripts/UploadsFile/uploadify.css" rel="stylesheet" />
    <script src="~/Scripts/UploadsFile/jquery.uploadify.js"></script>

2.页面中添加js代码:

    /*
    *  添加附件用
    */
    var typeFlagArray = [‘1‘];// 附件类型,同一页面多种类型时用数组按页面中的顺序依次写入数组,只有一种类型时只需写一个就可以
    var buttonText = ‘上 传‘; // 上传附件按钮显示的文本

3.页面html代码:

  1  <div class="tab-pane fade in active" id="BasicInfor">
  2                     <div style="margin-top:10px;">
  3                         <input type="hidden" value="@Model.ProjectID" name="ProjectID" id="ProjectID" />
  4                         <table class="basicTable">
  5                             <tr>
  6                                 <td class="td-right edu_width150"><span class="no_nullspan">*</span> 项目编号:</td>
  7                                 <td class="td-padding15"><input type="text" class="scinputlong" value="@Model.ProjectCode" name="ProjectCode" id="ProjectCode" maxlength="20" /></td>
  8                                 <td class="td-right"><span class="no_nullspan">*</span> 项目名称:</td>
  9                                 <td class="td-padding15"><input type="text" class="scinputlong" value="@Model.ProjectName" name="ProjectName" id="ProjectName" maxlength="100" /></td>
 10                             </tr>
 11                             <tr>
 12                                 <td class="td-right"><span class="no_nullspan">*</span> 企业名称:</td>
 13                                 <td class="td-padding15"><input type="text" class="scinputlong" value="@Model.EnterpriseName" name="EnterpriseName" id="EnterpriseName" maxlength="30" /></td>
 14                                 <td class="td-right"><span class="no_nullspan">*</span> 所属部门:</td>
 15                                 <td class="td-padding15">
 16                                     <select class="scselectlong" name="DepartmentID" id="DepartmentID" onchange="GetUser()"></select>
 17                             </tr>
 18                             <tr>
 19                                 <td class="td-right"><span class="no_nullspan">*</span> 项目负责人:</td>
 20                                 <td class="td-padding15">
 21                                     <select class="scselectlong" name="Principal" id="Principal"></select>
 22                                 </td>
 23                                 <td class="td-right"><span class="no_nullspan">*</span> 对应专业:</td>
 24                                 <td class="td-padding15">
 25                                     <input type="text" class="scinputlong" name="MajorID" id="MajorID" value="@Model.MajorID" maxlength="15" />
 26                                 </td>
 27                             </tr>
 28                             <tr>
 29                                 <td class="td-right"><span class="no_nullspan">*</span> 项目类型:</td>
 30                                 <td class="td-padding15">
 31                                     <select class="scselectlong" name="ProjectTypeID" id="ProjectTypeID"></select>
 32                                 </td>
 33                                 <td class="td-right"><span class="no_nullspan">*</span> 立项时间:</td>
 34                                 <td class="td-padding15">
 35                                     <div class="input-group date form_date" id="BeginDate_div">
 36                                         <input id="BeginDate" name="BeginDate" class="scinputtimelong" size="16" type="text" value="@Model.BeginDate.ToString("yyyy-MM-dd")" readonly>
 37                                         <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
 38                                     </div>
 39                                 </td>
 40                             </tr>
 41                             <tr>
 42                                 <td class="td-right">结项时间:</td>
 43                                 <td class="td-padding15">
 44                                     <div class="input-group date form_date" id="EndDate_div">
 45                                         <input id="EndDate" name="EndDate" class="scinputtimelong" size="16" type="text" value="@(Model.EndDate == null?"":Model.EndDate.Value.ToString("yyyy-MM-dd"))" readonly>
 46                                         <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
 47                                     </div>
 48                                 </td>
 49                                 <td class="td-right"><span class="no_nullspan">*</span> 项目状态:</td>
 50                                 <td class="td-padding15">
 51                                     <select class="scselectlong" name="ProjectState" id="ProjectState">
 52                                         @if (Model.ProjectState == 2)
 53                                         {
 54                                             <option value="1">立项</option>
 55                                             <option value="2" selected>结项</option>
 56                                         }
 57                                         else
 58                                         {
 59                                             <option value="1" selected>立项</option>
 60                                             <option value="2">结项</option>
 61                                         }
 62                                     </select>
 63                                 </td>
 64                             </tr>
 65                             <tr>
 66                                 <td class="td-right"><span class="no_nullspan">*</span> 合同经费(万元):</td>
 67                                 <td class="td-padding15"><input type="text" class="scinputlong" value="@Model.ContartAmount.ToString("0.###")" name="ContartAmount" id="ContartAmount" maxlength="19" /></td>
 68                                 <td class="td-right">到账经费(万元):</td>
 69                                 <td class="td-padding15"><input type="text" class="scinputlong" value="@Model.AccountAmount.ToString("0.###")" readonly="readonly" name="AccountAmount" id="AccountAmount" /></td>
 70                             </tr>
 71                             <tr>
 72                                 <td class="td-right"><input type="checkbox" name="PatentState" id="PatentState" @(Model.PatentState ? "checked=\"checked\"" : "") /> 是否申请专利 </td>
 73                                 <td colspan="3" class="td-padding15"><input type="checkbox" name="IdentifyState" id="IdentifyState" @(Model.IdentifyState ? "checked=\"checked\"" : "") /> 是否科委鉴定 </td>
 74                             </tr>
 75                             <tr>
 76                                 <td class="td-right"><span class="no_nullspan">*</span> 项目负责人职称:</td>
 77                                 <td class="td-padding15">
 78                                     <select class="scselectlong" name="PositionalTitles" id="PositionalTitles"></select>
 79                                 </td>
 80                                 <td class="td-right">备注:</td>
 81                                 <td class="td-padding15"><input type="text" class="scinputlong" value="@Model.Note" name="Note" id="Note" maxlength="250" /></td>
 82                             </tr>
 83                             <tr>
 84                                 <td class="td-right"><span class="no_nullspan">*</span> 立项附件:</td>
 85                                 <td class="td-padding15" colspan="3">
 86                                     @if (Model.ProjectState == 2)
 87                                     {
 88                                         <a class="" id="file_upload_begin_name" href="/Base/MyDownLoad?Filepath=@Model.BeginAttachmentPath" target="_blank">@Model.BeginAttachmentName</a>
 89                                     }
 90                                     else
 91                                     {
 92                                         <div id="file_upload_begin" class="file_upload"></div>
 93                                         <div id="" class="file_queue">
 94                                             <div class="file_queue_item  hidden" id="file_upload_begin_q">
 95                                                 <div class="cancel_item">
 96                                                     <a id="file_upload_begin_cancel" href="#" onclick="DelAttachment(‘file_upload_begin‘,‘@Model.BeginAttachmentName‘)">X</a>
 97                                                 </div>
 98                                                 <a class="" id="file_upload_begin_name" href="/Base/MyDownLoad?Filepath=@Model.BeginAttachmentPath" target="_blank">@Model.BeginAttachmentName</a>
 99                                             </div>
100                                         </div>
101                                     }
102                                     <input id="file_upload_begin_path" type="hidden" value="@Model.BeginAttachmentPath" />
103                                     <input id="file_upload_begin_guid" type="hidden" value="@Model.BeginAttachmentID" />
104                                 </td>
105 
106                             </tr>
107                             <tr>
108                                 <td class="td-right"><span class="no_nullspan">*</span> 结项附件:</td>
109                                 <td class="td-padding15" colspan="3">
110                                     @if (Model.ProjectState == 2)
111                                     {
112                                         <a class="" id="file_upload_end_name" href="/Base/MyDownLoad?Filepath=@Model.EndAttachmentPath" target="_blank">@Model.EndAttachmentName</a>
113                                     }
114                                     else
115                                     {
116                                         <div id="file_upload_end" class="file_upload"></div>
117                                         <div id="" class="file_queue">
118                                             <div class="file_queue_item  hidden" id="file_upload_end_q">
119                                                 <div class="cancel_item">
120                                                     <a id="file_upload_end_cancel" href="#" onclick="DelAttachment(‘file_upload_end‘,‘@Model.EndAttachmentName‘)">X</a>
121                                                 </div>
122                                                 <a class="" id="file_upload_end_name" href="/Base/MyDownLoad?Filepath=@Model.EndAttachmentPath" target="_blank">@Model.EndAttachmentName</a>
123                                             </div>
124                                         </div>
125 
126                                     }
127                                     <input id="file_upload_end_path" type="hidden" value="@Model.EndAttachmentPath" />
128                                     <input id="file_upload_end_guid" type="hidden" value="@Model.EndAttachmentID" />
129                                 </td>
130                             </tr>
131                             <tr>
132                                 <td class="td-right"><span class="no_nullspan">*</span> 合同附件:</td>
133                                 <td class="td-padding15" colspan="3">
134                                     @if (Model.ProjectState == 2)
135                                     {
136                                         <a class="" id="file_upload_contr_name" href="/Base/MyDownLoad?Filepath=@Model.ContractAttachmentPath" target="_blank">@Model.ContractAttachmentName</a>
137                                     }
138                                     else
139                                     {
140                                         <div id="file_upload_contr" class="file_upload"></div>
141                                         <div id="" class="file_queue">
142                                             <div class="file_queue_item  hidden" id="file_upload_contr_q">
143                                                 <div class="cancel_item">
144                                                     <a id="file_upload_contr_cancel" href="#" onclick="DelAttachment(‘file_upload_contr‘,‘@Model.ContractAttachmentName‘)">X</a>
145                                                 </div>
146                                                 <a class="" id="file_upload_contr_name" href="/Base/MyDownLoad?Filepath=@Model.ContractAttachmentPath" target="_blank">@Model.ContractAttachmentName</a>
147                                             </div>
148                                         </div>
149                                     }
150                                     <input id="file_upload_contr_path" type="hidden" value="@Model.ContractAttachmentPath" />
151                                     <input id="file_upload_contr_guid" type="hidden" value="@Model.ContractAttachmentID" />
152                                 </td>
153                             </tr>
154                         </table>
155                     </div>
156                     <div class="modal-footer">
157                         @if (Model.ProjectState == 2)
158                         {
159                             <button class="scbtn" onclick="">
160                                 保存
161                             </button>
162                         }
163                         else
164                         {
165                             <button class="scbtn addBtn" onclick="SaveBasicInfor()">
166                                 保存
167                             </button>
168                         }
169                     </div>
170                 </div>

 

4.将公用的js提到单独的js文件中(引用到页面结尾),代码如下:

  1 var typeFlag = ‘‘;
  2 var fileTypeExt = ‘*.*‘;
  3 
  4 /*
  5 * 附件上传
  6 */
  7 $(function () {
  8     var strPath = ‘‘;
  9     $(‘.file_upload‘).each(function (index, dom) {
 10         /*
 11         * 判断上传附件类型
 12         */
 13         if (typeFlagArray != undefined && typeFlagArray.length > 0){
 14             if (typeFlagArray.length === 1){
 15                 typeFlag = typeFlagArray[0];
 16             }
 17             else if (typeFlagArray.length > index) {
 18                 typeFlag=typeFlagArray[index];
 19             }
 20         }
 21         if (!IsNullOrEmptyOrUndefined(typeFlag)) {
 22             switch (typeFlag) {
 23                 case ‘1‘://文档类型
 24                     fileTypeExt = ‘*.doc;*.txt;*.ppt;*.xls;*.docx;*.xlsx;*.rar;*.zip;*.pdf‘;
 25                     break;
 26                 case ‘2‘://图片类型
 27                     fileTypeExt = ‘*.jpg;*.jpeg;*.png‘;
 28                     break;
 29                 case ‘3‘://flash 三维动画
 30                     fileTypeExt = ‘*.swf;*.flv‘;
 31                     break;
 32                 case ‘4‘:// pdf 文档
 33                     fileTypeExt = ‘*.pdf‘;
 34                     break;
 35                 default:
 36                     alert("初始化附件类型错误!");
 37                     return false;
 38             }
 39         }
 40 
 41         $(dom).uploadify({
 42             ‘swf‘: ‘/Scripts/UploadsFile/uploadify.swf‘,
 43             ‘buttonText‘: buttonText,
 44             ‘auto‘: true,
 45             ‘multi‘: false,
 46             //‘uploadLimit‘: 1,
 47             ‘queueSizeLimit‘: 1,
 48             ‘fileTypeExts‘: fileTypeExt,
 49             ‘formData‘: { ‘typeFlag‘: typeFlag },//此处修改附件类型
 50             ‘uploader‘: ‘/Base/uploadsAttachment‘,
 51             ‘fileSizeLimit‘: ‘30MB‘,
 52             //‘removeCompleted‘:false,//上传完成后jquery提供的文件显示是否自动消失
 53             ‘overrideEvents‘: [‘onSelectError‘, ‘onDialogClose‘],//重写onSelectError事件
 54             ‘onSelectError‘: function (file, errorCode, errorMsg) {
 55                 switch (errorCode) {
 56                     //-100
 57                     case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
 58                         alert("上传的文件数量已经超出系统限制的" + this.settings.queueSizeLimit + "个文件!");
 59                         break;
 60                         //-110
 61                     case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
 62                         alert("文件 [" + file.name + "] 大小超出系统限制的" + this.settings.fileSizeLimit + "大小!");
 63                         break;
 64                         //-120
 65                     case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
 66                         alert("文件 [" + file.name + "] 大小异常!");
 67                         break;
 68                 }
 69             },
 70             ‘onUploadComplete‘: function (file) {
 71                 $(‘#‘ + dom.id).addClass("hidden");
 72             },
 73             ‘onQueueComplete‘: function (data) {
 74             },
 75             ‘onUploadSuccess‘: function (file, data, response) {
 76                 //$(‘#‘ + file.id).find(‘.data‘).html(‘ 上传完毕‘);
 77                 var result = eval(‘(‘ + data + ‘)‘);
 78                 if (result.Success) {
 79                     var cancel = $(‘#‘ + dom.id + ‘_cancel‘);
 80                     var filedown = $(‘#‘ + dom.id + ‘_name‘);
 81 
 82                     if (filedown) {
 83                         filedown.text(result.FileName);
 84                         filedown[0].href = "/Base/MyDownLoad?Filepath=" + result.tempfilesPath;//临时文件夹路径
 85                         $(‘#‘ + dom.id + ‘_path‘).val(result.filesPath);//正式文件夹路径
 86                         $(‘#‘ + dom.id + ‘_guid‘).val(result.guid);
 87 
 88                         $(‘#‘ + dom.id + ‘_q‘).removeClass("hidden");
 89                     };
 90                     if (cancel) {
 91                         cancel[0].onclick = function () {
 92                             DelAttachment(dom.id, result.FileName);
 93                         };
 94                     };
 95                 }
 96                 else {
 97                     alert("上传文件失败:" + result.Message)
 98                 }
 99             },
100             ‘onUploadError‘: function (file, errorCode, errorMsg, errorString, swfuploadifyQueue) {
101                 alert("error");
102             },
103             ‘onCancel‘: function (event, ID, fileObj, data) {
104                 alert("cancel");
105             },
106         });
107 
108         //显示隐藏上传按钮,文件信息
109         var domfile= $(‘#‘ + dom.id + ‘_guid‘).val();
110         if (IsNullOrEmptyOrUndefined(domfile)) {
111             $(‘#‘ + dom.id + ‘_q‘).addClass("hidden");
112             $(‘#‘ + dom.id).removeClass("hidden");
113         }
114         else {
115             $(‘#‘ + dom.id + ‘_q‘).removeClass("hidden");
116             $(‘#‘ + dom.id).addClass("hidden");
117         }
118     })
119 });
120 
121 /*
122 * 删除附件
123 */
124 function DelAttachment(domID, fileName) {
125     if (confirm("您确认要删除附件【" + fileName + "】吗?删除点击“保存”后生效!")) {
126         $(‘#‘ + domID+‘_name‘).text("");
127         $(‘#‘ + domID+‘_name‘)[0].href = "#";
128         $(‘#‘ + domID + ‘_path‘).val(‘‘);
129         $(‘#‘ + domID + ‘_guid‘).val(‘‘);
130         $(‘#‘ + domID + ‘_q‘).addClass("hidden");
131         $(‘#‘ + domID).removeClass("hidden");
132     }
133 }

5.样式重写:

 .uploadify-queue {
        float: left;
    }

    .uploadify {
        float: left;
    }

    .uploadify-button {
        background-color: #87d6ff;
        background-image: -moz-linear-gradient(center bottom, #87d6ff 0%, #87d6ff 100%);
        background-position: center top;
        background-repeat: no-repeat;
        border: 2px solid #87d6ff;
        border-radius: 30px;
        color: #fff;
        font: bold 12px Arial,Helvetica,sans-serif;
        text-align: center;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
        width: 100%;
    }

        .uploadify-button :hover {
            background-color: #87d6ff;
            background-image: -moz-linear-gradient(center bottom, #87d6ff 0%, #87d6ff 100%);
        }

    .file_queue {
        float: left;
        margin-bottom: 1em;
    }

    .file_queue_item {
        background-color: #f5f5f5;
        border-radius: 3px;
        font: 11px Verdana,Geneva,sans-serif;
        margin-top: 5px;
        max-width: 350px;
        padding: 10px;
    }

        .file_queue_item .cancel_item a {
            /*background: rgba(0, 0, 0, 0) url("uploadify-cancel.png") no-repeat scroll 0 0;*/
            float: right;
            height: 16px;
            width: 16px;
            color: #555;
        }

 

遇到的问题及总结:

1.当上传按钮隐藏的js操作写在onUploadSuccess事件中时,页面上传完附件后jquery生成的附件信息显示块不会自动消失,页面js报错。

解决方案:将对上传按钮的隐藏操作“ $(‘#‘ + dom.id).addClass("hidden");”写到onUploadComplete事件中:

2.文件大小限制问题:当上传文件超过9M时就会报错,上传失败;

解决方案:.net本身有对上传文件的大小限制,修改配置文件<system.web>节点下的<httpRuntime targetFramework="4.6" />为(至少大于或等于上传插件中配置的文件大小):

<system.web>
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime maxRequestLength="51200"  targetFramework="4.6" />
  </system.web>

3.重写jquery生成的附件信息显示块中的删除事件:

 1 var cancel = $(‘#‘ + dom.id + ‘-queue .uploadify-queue-item[id="‘ + file.id + ‘"]‘).find(".cancel a");
 2 var filedown = $(‘#‘ + dom.id + ‘-queue .uploadify-queue-item[id="‘ + file.id + ‘"]‘).find(‘a[class="fileName"]‘);
 3 
 4 if (filedown) {
 5     filedown[0].href = "#";
 6     filedown.click(function (filepath) {
 7         alert("测试下载");
 8         //在这此处处理...    
 9     })
10 }
11 
12 if (cancel) {
13     //cancel.attr("rel", obj.Id);
14     cancel[0].href = "#";
15     cancel.click(function () {
16         if (confirm("您确认要删除该附件吗?"))                        {
17             alert("删除");
18 
19             $(‘#‘ + dom.id + ‘_name‘).text();
20             $(‘#‘ + dom.id + ‘_path‘).val();
21             $(‘#‘ + dom.id + ‘_guid‘).val();
22 
23             $(‘#‘ + dom.id).uploadify(‘cancel‘, file.id);
24         }
25         //在这此处处理...    
26     })
27 }

JQuery Uplodify上传附件(同一个页面多个uplodify控件解决方案)

标签:

原文地址:http://www.cnblogs.com/xiaoerlang90/p/5206576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!