ajaxFileUpload+struts2實現多檔案上傳(動態添加檔案上傳框)

來源:互聯網
上載者:User

標籤:ajaxfileupload   struts2   多檔案上傳   動態添加   

上篇文章http://blog.csdn.net/itmyhome1990/article/details/36396291介紹了ajaxfileupload實現多檔案上傳,

但只是固定的檔案個數,如果需求不確定是多少檔案 則我們就需要動態添加檔案上傳框,以實現靈活性。

基於上篇基本架構是不變的,主要修改以下幾個方面

1、jQuery實現動態添加刪除檔案上傳框

2、擷取檔案上傳框的ID

3、ajaxfileupload.js裡將ID數群組轉換為需要的Object數組

依次解決上面問題

一、實現動態添加刪除檔案上傳框

<body><form action="" enctype="multipart/form-data"><h2>多檔案上傳</h2><input type="file" id="file1" name="file" /><a id="add" href="javascript:void();" onclick="addFile();">添加</a><span><table id="down"></table></span></br><input type="button" onclick="fileUpload();" value="上傳"></form></body>
<script type="text/javascript">//添加附件 function addFile(){var fileLength = $("input[name=file]").length+1;var inputFile = "<div id=‘addFile"+fileLength+"‘><input type=‘file‘ id=‘file"+fileLength+"‘ name=‘file‘ />"+"<a href=‘javascript:void();‘ onclick=‘delFile("+fileLength+");‘>刪除</a></div>";$("#add").after(inputFile);}//刪除附件function delFile(id){$("#addFile"+id).remove();}</script>

二、擷取檔案上傳框的ID

由於我們不知道有多少個上傳框,每次添加一個上傳框,其id屬性都是以file1,file2方式遞增的

可以用each迴圈拼接字元

var files = "";//擷取所有 <input type="file" id="file1" name="file" /> 的ID屬性值 $("input[name=file]").each(function(){files = files + $(this).attr("id")+",";})//將字元最後一逗號(,)截取掉files = files.substring(0,files.length-1);
然後我們擷取的files值 如:var files = "file1,file2,file3";

可以使用console.info(typeof(files));查看files為string類型


三、ajaxfileupload.js裡將ID數群組轉換為需要的Object數組

因為我們需要的是諸如var files = [‘file1‘,‘file2‘,‘file3‘];

而不是var files = "file1,file2,file3";

所以需要進行轉換,其實也未必非得在ajaxfileupload.js裡進行操作

完全可以在擷取ID時轉換好 再傳值過來。也無所謂在哪裡了,方法都一樣。

還是找到以下代碼:

var oldElement = jQuery(‘#‘ + fileElementId);var newElement = jQuery(oldElement).clone();jQuery(oldElement).attr(‘id‘, fileId);jQuery(oldElement).before(newElement);jQuery(oldElement).appendTo(form);
在這段代碼之上添加如下:

var t = ‘‘;if(typeof(fileElementId) == ‘string‘){/* * 將傳過來的值 如:"file1,file2,file3" 轉換為:[‘file1‘,‘file2‘,‘file3‘]   */var s = fileElementId.split(",");for(var i in s){t = t +  "‘"+s[i]+"‘"+",";}t = "["+t+"]";  t = t.replace(",]", "]")}  fileElementId= eval(‘(‘+ t +‘)‘); //將string類型轉換為Object類型

效果

除了以上代碼其他如struts配置,Action無需修改

項目源碼下載:http://download.csdn.net/detail/itmyhome/7589939


歡迎加入JAVA技術交流群:74955800

轉載請註明出處:http://blog.csdn.net/itmyhome1990/article/details/36433621




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.