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

时间:2021-09-10 14:28:20

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

  <div class="tab-pane fade in active" id="BasicInfor">
<div style="margin-top:10px;">
<input type="hidden" value="@Model.ProjectID" name="ProjectID" id="ProjectID" />
<table class="basicTable">
<tr>
<td class="td-right edu_width150"><span class="no_nullspan">*</span> 项目编号:</td>
<td class="td-padding15"><input type="text" class="scinputlong" value="@Model.ProjectCode" name="ProjectCode" id="ProjectCode" maxlength="20" /></td>
<td class="td-right"><span class="no_nullspan">*</span> 项目名称:</td>
<td class="td-padding15"><input type="text" class="scinputlong" value="@Model.ProjectName" name="ProjectName" id="ProjectName" maxlength="100" /></td>
</tr>
<tr>
<td class="td-right"><span class="no_nullspan">*</span> 企业名称:</td>
<td class="td-padding15"><input type="text" class="scinputlong" value="@Model.EnterpriseName" name="EnterpriseName" id="EnterpriseName" maxlength="30" /></td>
<td class="td-right"><span class="no_nullspan">*</span> 所属部门:</td>
<td class="td-padding15">
<select class="scselectlong" name="DepartmentID" id="DepartmentID" onchange="GetUser()"></select>
</tr>
<tr>
<td class="td-right"><span class="no_nullspan">*</span> 项目负责人:</td>
<td class="td-padding15">
<select class="scselectlong" name="Principal" id="Principal"></select>
</td>
<td class="td-right"><span class="no_nullspan">*</span> 对应专业:</td>
<td class="td-padding15">
<input type="text" class="scinputlong" name="MajorID" id="MajorID" value="@Model.MajorID" maxlength="15" />
</td>
</tr>
<tr>
<td class="td-right"><span class="no_nullspan">*</span> 项目类型:</td>
<td class="td-padding15">
<select class="scselectlong" name="ProjectTypeID" id="ProjectTypeID"></select>
</td>
<td class="td-right"><span class="no_nullspan">*</span> 立项时间:</td>
<td class="td-padding15">
<div class="input-group date form_date" id="BeginDate_div">
<input id="BeginDate" name="BeginDate" class="scinputtimelong" size="16" type="text" value="@Model.BeginDate.ToString("yyyy-MM-dd")" readonly>
<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
</div>
</td>
</tr>
<tr>
<td class="td-right">结项时间:</td>
<td class="td-padding15">
<div class="input-group date form_date" id="EndDate_div">
<input id="EndDate" name="EndDate" class="scinputtimelong" size="16" type="text" value="@(Model.EndDate == null?"":Model.EndDate.Value.ToString("yyyy-MM-dd"))" readonly>
<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
</div>
</td>
<td class="td-right"><span class="no_nullspan">*</span> 项目状态:</td>
<td class="td-padding15">
<select class="scselectlong" name="ProjectState" id="ProjectState">
@if (Model.ProjectState == 2)
{
<option value="1">立项</option>
<option value="2" selected>结项</option>
}
else
{
<option value="1" selected>立项</option>
<option value="2">结项</option>
}
</select>
</td>
</tr>
<tr>
<td class="td-right"><span class="no_nullspan">*</span> 合同经费(万元):</td>
<td class="td-padding15"><input type="text" class="scinputlong" value="@Model.ContartAmount.ToString("0.###")" name="ContartAmount" id="ContartAmount" maxlength="19" /></td>
<td class="td-right">到账经费(万元):</td>
<td class="td-padding15"><input type="text" class="scinputlong" value="@Model.AccountAmount.ToString("0.###")" readonly="readonly" name="AccountAmount" id="AccountAmount" /></td>
</tr>
<tr>
<td class="td-right"><input type="checkbox" name="PatentState" id="PatentState" @(Model.PatentState ? "checked=\"checked\"" : "") /> 是否申请专利 </td>
<td colspan="3" class="td-padding15"><input type="checkbox" name="IdentifyState" id="IdentifyState" @(Model.IdentifyState ? "checked=\"checked\"" : "") /> 是否科委鉴定 </td>
</tr>
<tr>
<td class="td-right"><span class="no_nullspan">*</span> 项目负责人职称:</td>
<td class="td-padding15">
<select class="scselectlong" name="PositionalTitles" id="PositionalTitles"></select>
</td>
<td class="td-right">备注:</td>
<td class="td-padding15"><input type="text" class="scinputlong" value="@Model.Note" name="Note" id="Note" maxlength="250" /></td>
</tr>
<tr>
<td class="td-right"><span class="no_nullspan">*</span> 立项附件:</td>
<td class="td-padding15" colspan="3">
@if (Model.ProjectState == 2)
{
<a class="" id="file_upload_begin_name" href="/Base/MyDownLoad?Filepath=@Model.BeginAttachmentPath" target="_blank">@Model.BeginAttachmentName</a>
}
else
{
<div id="file_upload_begin" class="file_upload"></div>
<div id="" class="file_queue">
<div class="file_queue_item hidden" id="file_upload_begin_q">
<div class="cancel_item">
<a id="file_upload_begin_cancel" href="#" onclick="DelAttachment('file_upload_begin','@Model.BeginAttachmentName')">X</a>
</div>
<a class="" id="file_upload_begin_name" href="/Base/MyDownLoad?Filepath=@Model.BeginAttachmentPath" target="_blank">@Model.BeginAttachmentName</a>
</div>
</div>
}
<input id="file_upload_begin_path" type="hidden" value="@Model.BeginAttachmentPath" />
<input id="file_upload_begin_guid" type="hidden" value="@Model.BeginAttachmentID" />
</td> </tr>
<tr>
<td class="td-right"><span class="no_nullspan">*</span> 结项附件:</td>
<td class="td-padding15" colspan="3">
@if (Model.ProjectState == 2)
{
<a class="" id="file_upload_end_name" href="/Base/MyDownLoad?Filepath=@Model.EndAttachmentPath" target="_blank">@Model.EndAttachmentName</a>
}
else
{
<div id="file_upload_end" class="file_upload"></div>
<div id="" class="file_queue">
<div class="file_queue_item hidden" id="file_upload_end_q">
<div class="cancel_item">
<a id="file_upload_end_cancel" href="#" onclick="DelAttachment('file_upload_end','@Model.EndAttachmentName')">X</a>
</div>
<a class="" id="file_upload_end_name" href="/Base/MyDownLoad?Filepath=@Model.EndAttachmentPath" target="_blank">@Model.EndAttachmentName</a>
</div>
</div> }
<input id="file_upload_end_path" type="hidden" value="@Model.EndAttachmentPath" />
<input id="file_upload_end_guid" type="hidden" value="@Model.EndAttachmentID" />
</td>
</tr>
<tr>
<td class="td-right"><span class="no_nullspan">*</span> 合同附件:</td>
<td class="td-padding15" colspan="3">
@if (Model.ProjectState == 2)
{
<a class="" id="file_upload_contr_name" href="/Base/MyDownLoad?Filepath=@Model.ContractAttachmentPath" target="_blank">@Model.ContractAttachmentName</a>
}
else
{
<div id="file_upload_contr" class="file_upload"></div>
<div id="" class="file_queue">
<div class="file_queue_item hidden" id="file_upload_contr_q">
<div class="cancel_item">
<a id="file_upload_contr_cancel" href="#" onclick="DelAttachment('file_upload_contr','@Model.ContractAttachmentName')">X</a>
</div>
<a class="" id="file_upload_contr_name" href="/Base/MyDownLoad?Filepath=@Model.ContractAttachmentPath" target="_blank">@Model.ContractAttachmentName</a>
</div>
</div>
}
<input id="file_upload_contr_path" type="hidden" value="@Model.ContractAttachmentPath" />
<input id="file_upload_contr_guid" type="hidden" value="@Model.ContractAttachmentID" />
</td>
</tr>
</table>
</div>
<div class="modal-footer">
@if (Model.ProjectState == 2)
{
<button class="scbtn" onclick="">
保存
</button>
}
else
{
<button class="scbtn addBtn" onclick="SaveBasicInfor()">
保存
</button>
}
</div>
</div>

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

 var typeFlag = '';
var fileTypeExt = '*.*'; /*
* 附件上传
*/
$(function () {
var strPath = '';
$('.file_upload').each(function (index, dom) {
/*
* 判断上传附件类型
*/
if (typeFlagArray != undefined && typeFlagArray.length > 0){
if (typeFlagArray.length === 1){
typeFlag = typeFlagArray[0];
}
else if (typeFlagArray.length > index) {
typeFlag=typeFlagArray[index];
}
}
if (!IsNullOrEmptyOrUndefined(typeFlag)) {
switch (typeFlag) {
case '1'://文档类型
fileTypeExt = '*.doc;*.txt;*.ppt;*.xls;*.docx;*.xlsx;*.rar;*.zip;*.pdf';
break;
case '2'://图片类型
fileTypeExt = '*.jpg;*.jpeg;*.png';
break;
case '3'://flash 三维动画
fileTypeExt = '*.swf;*.flv';
break;
case '4':// pdf 文档
fileTypeExt = '*.pdf';
break;
default:
alert("初始化附件类型错误!");
return false;
}
} $(dom).uploadify({
'swf': '/Scripts/UploadsFile/uploadify.swf',
'buttonText': buttonText,
'auto': true,
'multi': false,
//'uploadLimit': 1,
'queueSizeLimit': 1,
'fileTypeExts': fileTypeExt,
'formData': { 'typeFlag': typeFlag },//此处修改附件类型
'uploader': '/Base/uploadsAttachment',
'fileSizeLimit': '30MB',
//'removeCompleted':false,//上传完成后jquery提供的文件显示是否自动消失
          'removeTimeout':0,/上传完成后jquery提供的文件显示自动消失延时时间
'overrideEvents': ['onSelectError', 'onDialogClose'],//重写onSelectError事件
'onSelectError': function (file, errorCode, errorMsg) {
switch (errorCode) {
//-100
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
alert("上传的文件数量已经超出系统限制的" + this.settings.queueSizeLimit + "个文件!");
break;
//-110
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
alert("文件 [" + file.name + "] 大小超出系统限制的" + this.settings.fileSizeLimit + "大小!");
break;
//-120
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
alert("文件 [" + file.name + "] 大小异常!");
break;
}
},
'onUploadComplete': function (file) {
$('#' + dom.id).addClass("hidden");
},
'onQueueComplete': function (data) {
},
'onUploadSuccess': function (file, data, response) {
//$('#' + file.id).find('.data').html(' 上传完毕');
var result = eval('(' + data + ')');
if (result.Success) {
var cancel = $('#' + dom.id + '_cancel');
var filedown = $('#' + dom.id + '_name'); if (filedown) {
filedown.text(result.FileName);
filedown[0].href = "/Base/MyDownLoad?Filepath=" + result.tempfilesPath;//临时文件夹路径
$('#' + dom.id + '_path').val(result.filesPath);//正式文件夹路径
$('#' + dom.id + '_guid').val(result.guid); $('#' + dom.id + '_q').removeClass("hidden");
};
if (cancel) {
cancel[0].onclick = function () {
DelAttachment(dom.id, result.FileName);
};
};
}
else {
alert("上传文件失败:" + result.Message)
}
},
'onUploadError': function (file, errorCode, errorMsg, errorString, swfuploadifyQueue) {
alert("error");
},
'onCancel': function (event, ID, fileObj, data) {
alert("cancel");
},
}); //显示隐藏上传按钮,文件信息
var domfile= $('#' + dom.id + '_guid').val();
if (IsNullOrEmptyOrUndefined(domfile)) {
$('#' + dom.id + '_q').addClass("hidden");
$('#' + dom.id).removeClass("hidden");
}
else {
$('#' + dom.id + '_q').removeClass("hidden");
$('#' + dom.id).addClass("hidden");
}
})
}); /*
* 删除附件
*/
function DelAttachment(domID, fileName) {
if (confirm("您确认要删除附件【" + fileName + "】吗?删除点击“保存”后生效!")) {
$('#' + domID+'_name').text("");
$('#' + domID+'_name')[0].href = "#";
$('#' + domID + '_path').val('');
$('#' + domID + '_guid').val('');
$('#' + domID + '_q').addClass("hidden");
$('#' + domID).removeClass("hidden");
}
}

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生成的附件信息显示块中的删除事件:

 var cancel = $('#' + dom.id + '-queue .uploadify-queue-item[id="' + file.id + '"]').find(".cancel a");
var filedown = $('#' + dom.id + '-queue .uploadify-queue-item[id="' + file.id + '"]').find('a[class="fileName"]'); if (filedown) {
filedown[0].href = "#";
filedown.click(function (filepath) {
alert("测试下载");
//在这此处处理...
})
} if (cancel) {
//cancel.attr("rel", obj.Id);
cancel[0].href = "#";
cancel.click(function () {
if (confirm("您确认要删除该附件吗?")) {
alert("删除"); $('#' + dom.id + '_name').text();
$('#' + dom.id + '_path').val();
$('#' + dom.id + '_guid').val(); $('#' + dom.id).uploadify('cancel', file.id);
}
//在这此处处理...
})
}