欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jquery实现动态添加附件功能

程序员文章站 2023-01-10 11:47:31
本文实例为大家分享了jquery实现动态添加附件的具体代码,供大家参考,具体内容如下 创建html页面 项目中实现的原代码,无删减直接贴上。具体请参考“添加附件”按...

本文实例为大家分享了jquery实现动态添加附件的具体代码,供大家参考,具体内容如下

创建html页面

项目中实现的原代码,无删减直接贴上。具体请参考“添加附件”按钮相关操作。
注意引入:cardransommanage.js,ajaxfileupload.js.

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<#include "../ftl/includes/easyui.ftl"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>账户管理-预付卡赎回管理</title>
</head>
<body class="easyui-layout" fit="true">
 <div class="w_960 mg_auto">
  <div class="over_f_h">
   <div class="mg_t_10 font_13">
    当前位置:预付费卡综合管理系统 > 预付卡赎回管理 > 
    <a class="color_000 hover_nav_link" href="${rc.contextpath}/ransom/apply" rel="external nofollow" >赎回申请</a> > 
   </div>
   <form id="editform" method="post" enctype="multipart/form-data">
    <input type="hidden" name="isloginuser" id="isloginuser" value=${isloginuser?string} />
    <input type="hidden" name="orderstatus" id="orderstatus" value='${order.orderstatus!}' />
    <div class="mg_t_10 bd_ccc pd_b_20">
     <div class="h_30 bg_fff4c8 font_w_bold font_13 line_2p4em pd_l_10 bd_b_ccc">赎回申请</div>
     <div id="toolbar" class="datagrid-toolbar" style="height: auto;">
      <a id="btnaddfile" class="easyui-linkbutton" iconcls="icon-add" plain="true" onclick="javascript:addfile();">增加附件</a>
      <a id="btnsave" class="easyui-linkbutton" iconcls="icon-save" plain="true" onclick="javascript:savefile();">上传附件并保存</a>
      <@verifyres res="/ransom/ransominvalid?apply">
      <a id="btnsubmit" class="easyui-linkbutton" iconcls="icon-ok" plain="true" onclick="javascript:submitapply();">申    请</a>
      </@verifyres>
      <@verifyres res="/ransom/ransominvalid?audit">
      <a id="btnaudit" class="easyui-linkbutton" iconcls="icon-ok" plain="true" onclick="javascript:submitaudit();">审    核</a>
      <a id="btnrefuse" class="easyui-linkbutton" iconcls="icon-ok" plain="true" onclick="javascript:submitrefuse();">驳    回</a>
      </@verifyres>
      <div class="clear"></div>
     </div>
     <div>
      <div class="mg_auto mg_t_30 pd_l_30">
       <div class="f_l w_350">
        <div class="f_l mg_t_2 w_120 a_r val_input">赎回单号:</div>
        <input type="text" name="orderno" id="orderno" value='${order.orderno!}' disabled="disabled" class="f_l show h_20 line_1p7em w_150 required"/>
        <div class="clear"></div>
       </div>
       <div class="clear"></div>
      </div>
      <div class="mg_auto mg_t_10 pd_l_30">
       <div class="f_l w_350">
        <div class="f_l mg_t_2 w_120 a_r val_input">申请人:</div>
        <input type="text" name="createname" id="createname" value='${order.createname}' disabled="disabled" class="f_l show h_20 line_1p7em w_150 required"/>
        <div class="clear"></div>
       </div>
       <div class="clear"></div>
      </div>

      <div class="mg_auto mg_t_10 pd_l_30">
       <div class="f_l w_350">
        <div class="f_l mg_t_2 w_120 a_r val_input">表单状态:</div>
        <select class="f_l show h_20 line_1p7em required w_150" id="orderstatus" name="orderstatus" disabled="disabled">
         <option class="h_20" value="" >--全部--</option>
         <#if ransomstatus??>
          <#list ransomstatus as es>
           <option value='${es.value!}'
            <#if order.orderstatus?exists><#if order.orderstatus==es.value> selected="selected"</#if></#if>>${es.chname!""}</option>
          </#list>
         </#if>
        </select>
        <div class="clear"></div>
       </div>
       <div class="clear"></div>
      </div>

      <div id="freshdiv"></div>
      <div class="mdiv" id="mdiv">
       <#if order.attachment??>
       <#list order.attachment as attach>
       <div class="mg_auto mg_t_10 pd_l_30" style="disabled:true">
        <div class="f_l w_600">
         <div class="f_l mg_t_2 w_120 a_r val_input">附件(已上传):</div>
          <input type="text" name="attach" value="${attach.attachmentpath}" disabled="disabled" class="f_l show h_20 line_1p7em w_150 required"/>  
          <a href="#" rel="external nofollow" rel="external nofollow" name="rmlinkattach" onclick="rmlinkattach('${attach.attachmentid}',this)" style="color:red">删除</a>
          <a href="javascript:void(0)" rel="external nofollow" onclick="downloadfile('${attach.attachmentid}')">下载</a>
         <div class="clear"></div>
        </div>
        <div class="clear"></div>
       </div>
       </#list>
       </#if>
      </div>
     </div>
    </div>
   </form>
  </div>
 </div>

 <div id="filetemplate" style="display:none">
  <div class="mg_auto mg_t_10 pd_l_30">
   <div class="f_l w_600">
    <div class="f_l mg_t_2 w_120 a_r val_input">附件:</div>
     <input type="file" name="uploadfiles0" class="f_l show h_20 line_1p7em w_220 required" />  
     <a href="#" rel="external nofollow" rel="external nofollow" name="rmlink0" style="color:red">删除 </a>
    <div class="clear"></div>
   </div>
   <div class="clear"></div>
  </div>
 </div>
 <form action="" id="downloadform" method="post">
  <input type="hidden" name="attachmentid" id="attachmentid"/>
 </form>
 <div id="loading" class="pos_ab pd_b_30 font_15 font_msyh bd_2_4979e8 bd_radius_5 bg_fff color_333333 z_index_600 hide" >
  <div class="f_c show w_50 h_50 vlbc_customeradd mg_l_120 mg_r_120 mg_t_24"></div>
  <div class="mg_t_24 mg_l_60 mg_r_60">正在处理,请稍后...</div>
 </div>

 <script type="text/javascript" charset="utf-8" src="${rc.contextpath}/js/ransom/cardransommanage.js"></script>
 <script type="text/javascript" charset="utf-8" src="${rc.contextpath}/js/card/ajaxfileupload.js"></script>
</body>
</html>

创建javascript库

cardransommanage.js

//设置面罩的z-index,打开进度条
function setpopupz_index() {
 $("#popupdiv_bgdiv_1").css("z-index", "550");
 bcd_openpopupdailog(300, 'loading'); //进度条
}

/**
 * 编辑、查看、提交页面 资源控制
*/
var $filemixsize = 10; //允许上传附件数
var $filecursize = 0; //已上传并保存附件数
var $filesize = 0;  //当前新增附件操作次数
var $delfiles ="";  //记录 删除已保存附件
var $flag = 0;  //数据校验 0:附件无效; 1:无附件提交; 2:附件有效

$(document).ready(function(){
 $filecursize = $("input[name='attach']").size();
 initialresource();
 bindlistener();
});

function initialresource(){
 var orderstatus = $("#orderstatus").val();
 var isloginuser = $("#isloginuser").val();
 var btnsubmit = $("#btnsubmit");
 var btnaudit = $("#btnaudit");
 var btnrefuse = $("#btnrefuse");

 if(isloginuser=="true"){
  if(orderstatus==0||orderstatus==3){//草稿、驳回状态
//   addfile();
   if(btnaudit != undefined){
    btnaudit.hide();
   }
   if(btnrefuse != undefined){
    btnrefuse.hide();
   }
  }else {//orderstatus:1(申请),2(审核)
   $("a[name='rmlinkattach']").remove();
   $("#toolbar").remove();
  }
 }else{
  if(orderstatus!=1){
   $("#toolbar").remove();
   $("a[name='rmlinkattach']").remove();
  }else{
   $("#btnsave").hide();
   $("a[name='rmlinkattach']").hide();
   if(btnsubmit != undefined){
    btnsubmit.hide();
   }
  }
 }
}

function doclosefunction(){
 window.location.href="query?orderdetail&orderno=" rel="external nofollow" ;
}

function addfile(){ 
 $filesize = $("[name='uploadfiles']").size();
 if($filesize < $filemixsize - $filecursize){
  var $filetemple=$("#filetemplate >div").clone();
  var tid = "uploadfiles0"+new date().gettime();
  $filetemple.find(":file").attr("id",tid);
  $filetemple.find(":file").attr("name","uploadfiles");
  $filetemple.find("a").attr("name","rmlink");
  $("#mdiv").append($filetemple);
  bindlistener();
  $filesize++;
 }else{
  alertdiv.create("alertdiv","最大上传文件数为:"+$filemixsize+".");
 }
}

function savefile(){ 
 opersubmit("0");
 $delfiles = "";
} 

function submitapply(){ 
 opersubmit("1");
 $delfiles ="";
}

function submitaudit(){ 
 var orderstatus = $("#orderstatus").val();
 //审核人:只允许处理审核状态的赎回单
 if(orderstatus==1){
  $.messager.confirm('请确认', '您要批准此赎回申请单?', function(r) {
   if(r){
    opersubmit("2"); //审批通过
   }
  });
  $delfiles ="";
 }else{
  alertdiv.create("alertdiv","赎回单当前状态,不允许提交!");
 }
}

function submitrefuse(){
 var orderstatus = $("#orderstatus").val();
 //审核人:只允许处理审核状态的赎回单
 if(orderstatus==1){
  $.messager.confirm('请确认', '您要驳回此赎回申请单?', function(r) {
   if(r){
    opersubmit("3"); //驳回
   }
  });
 }else{
  alertdiv.create("alertdiv","赎回单当前状态,不允许提交!");
 }
}

function downloadfile(attachmentid){
 $('#attachmentid').val(attachmentid);
 $('#downloadform').attr('action', 'download');
 $("#downloadform").submit();
}

function bindlistener(){
  $("a[name=rmlink]").unbind().click(function(){
   $(this).parent().parent().remove(); 
   $filesize--;
  })
}

function rmlinkattach(attach, obj){
 $.messager.confirm('请确认', '您要删除当前所选项目?', function(r) {
  if(r){
   $delfiles += ""+attach +",";
   $filecursize -=1;
   $(obj).parent().parent().remove(); 
  }
 });

}

//处理查询返回的信息
function callback(order) {
 var html = "";
 var orderstatus = order.orderstatus;
 //var orderstatus = record['record'].orderstatus;
 $("#orderstatus").val(orderstatus);
 $("#mdiv").empty();//清空以前的数据
 $("#freshdiv").empty();
 $(order.attachment).each(
   function(i, attach) {
    html += "<div class='mg_auto mg_t_10 pd_l_30' style='disabled:true'>";
    html += " <div class='f_l w_600'>";
    html += "  <div class='f_l mg_t_2 w_120 a_r val_input'>附件(已上传):</div>";
    html += "   <input type='text' name='attach' value=" + attach.attachmentpath + " disabled='disabled' class='f_l show h_20 line_1p7em w_150 required'/> &nbsp";
    if(orderstatus==0||orderstatus==3){
     html += "   <a href='#' name='rmlinkattach' onclick='rmlinkattach(" + attach.attachmentid + ",this)' style='color:red'>删除</a>";
    }
    html += "   <a href='javascript:void(0)' onclick='downloadfile(" + attach.attachmentid + ")'>下载</a>";
    html += "  <div class='clear'></div>";
    html += " </div>";
    html += " <div class='clear'></div>";
    html += "</div>";
   });

 var $container = $("#freshdiv");
 $container.append(html);//追加新的数据
}

function refreshres(order,orderstatusname){
 $("#orderno").val(order.orderno);
 $("#orderstatus").val(order.orderstatus);
 $("#orderstatus option[value='"+order.orderstatus+"']").attr("selected","selected");
 initialresource();
 //$.post("query?detail",order,callback, "json");
 callback(order)
 $filecursize = $("input[name='attach']").size();
}

function opersubmit(status){
 validateuploadfiles();
 if($flag==2){
  var order = {
   orderno: $("#orderno").val(),
   orderstatus: status,
   attachments: $delfiles
  };
  fileupload("save",order,"query?orderdetail&orderno=");

 }else if($flag==1){
  var order = {
   orderno: $("#orderno").val(),
   orderstatus: status, 
   attachments: $delfiles
  };
  $.post("save?unupload", order,
   function(data){
    if (data.success) {
     refreshres(data['order']);
     alertdiv.create("alertdiv", data.obj);
    } else {
     alertdiv.create("alertdiv", data.obj);
    }
   }, "json");
 }else{
  alertdiv.create("alertdiv","附件不能为空,请添加有效附件!");
 }
}

function validateuploadfiles(){
 var files = $("input[name='uploadfiles']");
 if(files.size()>0){
  $.each(files,function(i, file){
   if(file.value==undefined || file.value==""){
    alertdiv.create("alertdiv","新增附件不能为空,请上传!");
    $flag = 0;
   }else{
    $flag = 2;
   }
  });
 }else{
  $flag=1;
 }
}

function fileupload(url,order,successurl){
 var files = $("input[name='uploadfiles']");
 var uploadfiles = [];
 $.each(files,function(i, file){
  if(file.value!=undefined || file.value!=""){
   uploadfiles.push(files[i].id)
  }
 });
 $.ajaxfileupload({
  url: url, 
  secureuri : false,
  type: 'post', 
  datatype: "json", 
  fileelementid: uploadfiles,
  data: order, 
  beforesend: function() {
   setpopupz_index();
  }, 
  success: function(result) {
   if (result.success) {
    refreshres(result['order']);
    alertdiv.create("alertdiv", result.obj);
   } else {
    alertdiv.create("alertdiv", result.obj);
   }
  },
  error: function(result) {
   alertdiv.create("alertdiv", "赎回申请信息出错,请稍后重试!");
  }, 
  complete: function() {
   //$("#btnsave").removeattr("disabled");

  }
 });
}

ajaxfileupload.js

jquery.extend({

  handleerror: function( s, xhr, status, e )   {
    // if a local callback was specified, fire it
        if ( s.error ) {
          s.error.call( s.context || s, xhr, status, e );
        }

        // fire the global callback
        if ( s.global ) {
          (s.context ? jquery(s.context) : jquery.event).trigger( "ajaxerror", [xhr, s, e] );
        }
      },

  createuploadiframe: function(id, uri)
  {
      //create frame
      var frameid = 'juploadframe' + id;
      var iframehtml = '<iframe id="' + frameid + '" name="' + frameid + '" style="position:absolute; top:-9999px; left:-9999px"';
      if(window.activexobject)
      {
        if(typeof uri== 'boolean'){
          iframehtml += ' src="' + 'javascript:false' + '"';

        }
        else if(typeof uri== 'string'){
          iframehtml += ' src="' + uri + '"';

        }  
      }
      iframehtml += ' />';
      jquery(iframehtml).appendto(document.body);

      return jquery('#' + frameid).get(0);      
  },
  createuploadform: function(id, fileelementid, data)
  {
    //create form  
    var formid = 'juploadform' + id;
    var fileid = 'juploadfile' + id;
    var form = jquery('<form action="" method="post" name="' + formid + '" id="' + formid + '" enctype="multipart/form-data"></form>');  
    if(data)
    {
      for(var i in data)
      {
        jquery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendto(form);
      }      
    }   

    if(typeof(fileelementid) == 'string'){ 
      fileelementid = [fileelementid]; 
    } 
    for (var i = 0; i < fileelementid.length; i ++) { 
      var oldelement = jquery('#' + fileelementid[i]); 
      var newelement = jquery(oldelement).clone(); 
      jquery(oldelement).attr('id', fileid); 
      jquery(oldelement).before(newelement); 
      jquery(oldelement).appendto(form); 
    }
//   var oldelement = jquery('#' + fileelementid);
//   var newelement = jquery(oldelement).clone();
//   jquery(oldelement).attr('id', fileid);
//   jquery(oldelement).before(newelement);
//   jquery(oldelement).appendto(form);


    //set attributes
    jquery(form).css('position', 'absolute');
    jquery(form).css('top', '-1200px');
    jquery(form).css('left', '-1200px');
    jquery(form).appendto('body');   
    return form;
  },

  ajaxfileupload: function(s) {
    // todo introduce global settings, allowing the client to modify them for all requests, not only timeout    
    s = jquery.extend({}, jquery.ajaxsettings, s);
    var id = new date().gettime()    
    var form = jquery.createuploadform(id, s.fileelementid, (typeof(s.data)=='undefined'?false:s.data));
    var io = jquery.createuploadiframe(id, s.secureuri);
    var frameid = 'juploadframe' + id;
    var formid = 'juploadform' + id;    
    // watch for a new set of requests
    if ( s.global && ! jquery.active++ )
    {
      jquery.event.trigger( "ajaxstart" );
    }      
    var requestdone = false;
    // create the request object
    var xml = {}  
    if ( s.global )
      jquery.event.trigger("ajaxsend", [xml, s]);
    // wait for a response to come back
    var uploadcallback = function(istimeout)
    {      
      var io = document.getelementbyid(frameid);
      try 
      {        
        if(io.contentwindow)
        {
           xml.responsetext = io.contentwindow.document.body?io.contentwindow.document.body.innerhtml:null;
           xml.responsexml = io.contentwindow.document.xmldocument?io.contentwindow.document.xmldocument:io.contentwindow.document;

        }else if(io.contentdocument)
        {
           xml.responsetext = io.contentdocument.document.body?io.contentdocument.document.body.innerhtml:null;
          xml.responsexml = io.contentdocument.document.xmldocument?io.contentdocument.document.xmldocument:io.contentdocument.document;
        }            
      }catch(e)
      {
        jquery.handleerror(s, xml, null, e);
      }
      if ( xml || istimeout == "timeout") 
      {        
        requestdone = true;
        var status;
        try {
          status = istimeout != "timeout" ? "success" : "error";
          // make sure that the request was successful or notmodified
          if ( status != "error" )
          {
            // process the data (runs the xml through httpdata regardless of callback)
            var data = jquery.uploadhttpdata( xml, s.datatype );  
            // if a local callback was specified, fire it and pass it the data
            if ( s.success )
              s.success( data, status );

            // fire the global callback
            if( s.global )
              jquery.event.trigger( "ajaxsuccess", [xml, s] );
          } else
            jquery.handleerror(s, xml, status);
        } catch(e) 
        {
          status = "error";
          jquery.handleerror(s, xml, status, e);
        }

        // the request was completed
        if( s.global )
          jquery.event.trigger( "ajaxcomplete", [xml, s] );

        // handle the global ajax counter
        if ( s.global && ! --jquery.active )
          jquery.event.trigger( "ajaxstop" );

        // process result
        if ( s.complete )
          s.complete(xml, status);

        jquery(io).unbind()

        settimeout(function()
                  {  try 
                    {
                      jquery(io).remove();
                      jquery(form).remove(); 

                    } catch(e) 
                    {
                      jquery.handleerror(s, xml, null, e);
                    }                 

                  }, 100)

        xml = null

      }
    }
    // timeout checker
    if ( s.timeout > 0 ) 
    {
      settimeout(function(){
        // check to see if the request is still happening
        if( !requestdone ) uploadcallback( "timeout" );
      }, s.timeout);
    }
    try 
    {

      var form = jquery('#' + formid);
      jquery(form).attr('action', s.url);
      jquery(form).attr('method', 'post');
      jquery(form).attr('target', frameid);
      if(form.encoding)
      {
        jquery(form).attr('encoding', 'multipart/form-data');        
      }
      else
      {  
        jquery(form).attr('enctype', 'multipart/form-data');      
      }      
      jquery(form).submit();

    } catch(e) 
    {      
      jquery.handleerror(s, xml, null, e);
    }

    jquery('#' + frameid).load(uploadcallback  );
    return {abort: function () {}};

  },

  uploadhttpdata: function( r, type ) {
    var data = !type;
    data = type == "xml" || data ? r.responsexml : r.responsetext;
    // if the type is "script", eval it in global context
    if ( type == "script" )
      jquery.globaleval( data );
    // get the javascript object, if json is used.
    if ( type == "json" )

       data = r.responsetext; 
      var start = data.indexof(">"); 
    if(start != -1) { 
     var end = data.indexof("<", start + 1); 
     if(end != -1) { 
      data = data.substring(start + 1, end); 
      } 
    } 
      eval( "data = " + data );
    // evaluate scripts within html
    if ( type == "html" )
      jquery("<div>").html(data).evalscripts();

    return data;
  }
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。