打開google 搜索"ajaxFileupload' ‘多文件上傳"可以搜到許許多多類似的,那我為什么還要寫一下呢?
一個是對之前大神的貢獻表示感謝;二個是自己知識的總結;三個是自己在原有的基礎上改動了下,在此記錄,可能幫助其他朋友。
用過這個插件的都知道這個插件的基本用法,我就不廢話,直接上代碼。
我需要實現多個文件上傳,之前的做法是定義多個不同id的input,然后把ajaxfileuplod方法放在for循環里,這個方法是在網上看到的,我覺得不怎么好,后面在網上找到的,就高級點了,直接改源碼(因為作者好久沒有跟新了,也確實滿足不了要求了)。接下來看看我是怎么改的。
引用網上的做法:
1、看沒有修改前的代碼
var oldElement = jQuery('#' + fileElementId); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form);
很容易看出,這個就是把id為什么的input加到from里去,那么要實現多個文件上傳,就改成下面的樣子:
if(typeof(fileElementId) == 'string'){ fileElementId = [fileElementId]; } for(var i in fileElementId){ var oldElement = jQuery('#' + fileElementId[i]); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); }
這樣改之后,初始化的代碼就要這么寫:
$.ajaxFileUpload({ url:'/ajax.php', fileElementId:['id1','id2']//原先是fileElementId:'id' 只能上傳一個 });
到這里,確實可以上傳多個文件,但是對于我來說新問題又來,多個id,我的界面的文件不是固定的,是動態加載的,那么id要動態生成,我覺得太麻煩,為什么不取name呢?然后把以上代碼改為如下:
if(typeof(fileElementId) == 'string'){ fileElementId = [fileElementId]; } for(var i in fileElementId){ //按name取值 var oldElement = jQuery("input[name="+fileElementId[i]+"]"); oldElement.each(function() { var newElement = jQuery($(this)).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); }); }
這樣改了 那么就可以實現多組多個文件上傳,接下來看我是怎么應用的。
html:
<div> <img id="loading" src="scripts/ajaxFileUploader/loading.gif" style="display:none;"> <table cellpadding="0" cellspacing="0" class="tableForm" id="calculation_model"> <thead> <tr> <th>多組多個文件</th> </tr> </thead> <tbody> <tr> <td>第一組</td> <td>第二組</td> </tr> <tr> <td><input type="file" name="gridDoc" class="input"></td> <td><input type="file" name="caseDoc" class="input"></td> </tr> </tbody> <tfoot> <tr> <td><button class="button" id="up1">Upload</button></td> <td><button class="button" id="addInput" >添加一組</button></td> </tr> </tfoot> </table> </div>
新聞熱點
疑難解答
圖片精選