使用ajaxFileupload实现多文件批量上传

转自:http://blog.csdn.net/zhanglu201112/article/details/17039137


打开google 搜索 ‘ajaxFileupload’ ‘多文件上传’ 可以搜到许许多多类似的,那我为什么还要写一下呢?

一个是对之前大神的贡献表示感谢;二个是自己知识的总结;三个是自己在原有的基础上改动了下,在此记录,可能帮助其他朋友。

用过这个插件的都知道这个插件的基本用法,我就不废话,直接上代码。

我需要实现多个文件上传,之前的做法是定义多个不同id的input,然后把ajaxfileuplod方法放在for循环里,这个方法是在网上看到的,我觉得不怎么好,后面在网上找到的,就高级点了,直接改源码(因为作者好久没有跟新了,也确实满足不了要求了)。接下来看看我是怎么改的。

引用网上的做法:

1,看没有修改前的代码

Js代码   收藏代码
  1. var oldElement = jQuery('#' + fileElementId);  
  2. var newElement = jQuery(oldElement).clone();  
  3. jQuery(oldElement).attr('id', fileId);  
  4. jQuery(oldElement).before(newElement);  
  5. jQuery(oldElement).appendTo(form);  

 

很容易看出,这个就是把id为什么的input加到from里去,那么要实现多个文件上传,就改成下面的样子:

Js代码   收藏代码
  1. if(typeof(fileElementId) == 'string'){  
  2.     fileElementId = [fileElementId];  
  3. }  
  4. for(var i in fileElementId){  
  5.     var oldElement = jQuery('#' + fileElementId[i]);  
  6.     var newElement = jQuery(oldElement).clone();  
  7.     jQuery(oldElement).attr('id', fileId);  
  8.     jQuery(oldElement).before(newElement);  
  9.     jQuery(oldElement).appendTo(form);  
  10. }  

 这样改之后,初始化的代码就要这么写:

Js代码   收藏代码
  1. $.ajaxFileUpload({  
  2.     url:'/ajax.php',  
  3.     fileElementId:['id1','id2']//原先是fileElementId:’id’ 只能上传一个  
  4. });  

 到这里,确实可以上传多个文件,但是对于我来说新问题又来,多个id,我的界面的文件不是固定的,是动态加载的,那么id要动态生成,我觉得太麻烦,为什么不取name呢?然后把以上代码改为如下:

Js代码   收藏代码
  1. if(typeof(fileElementId) == 'string'){  
  2.            fileElementId = [fileElementId];  
  3.        }  
  4.        for(var i in fileElementId){  
  5.            //按name取值  
  6.            var oldElement = jQuery("input[name="+fileElementId[i]+"]");  
  7.            oldElement.each(function() {  
  8.                var newElement = jQuery($(this)).clone();  
  9.                jQuery(oldElement).attr('id', fileId);  
  10.                jQuery(oldElement).before(newElement);  
  11.                jQuery(oldElement).appendTo(form);  
  12.            });  
  13.        }  

 这样改了 那么就可以实现多组多个文件上传,接下来看我是怎么应用的。

html:

Html代码   收藏代码
  1. <div>  
  2.               <img id="loading" src="scripts/ajaxFileUploader/loading.gif" style="display:none;">  
  3.              
  4.                   <table cellpadding="0" cellspacing="0" class="tableForm" id="calculation_model">  
  5.                       <thead>  
  6.                       <tr>  
  7.                           <th>多组多个文件</th>  
  8.                       </tr>  
  9.                       </thead>  
  10.                       <tbody>  
  11.                       <tr>  
  12.                           <td>第一组</td>  
  13.                           <td>第二组</td>  
  14.                       </tr>  
  15.                       <tr>  
  16.                           <td><input type="file"  name="gridDoc" class="input"></td>  
  17.                           <td><input type="file" name="caseDoc" class="input"></td>  
  18.                       </tr>  
  19.                       </tbody>  
  20.                       <tfoot>  
  21.                       <tr>  
  22.                           <td><button class="button" id="up1">Upload</button></td>  
  23.                           <td><button class="button" id="addInput" >添加一组</button></td>  
  24.                       </tr>  
  25.                       </tfoot>  
  26.                   </table>  
  27.           </div>  

 js:

Js代码   收藏代码
  1. /** 
  2.  * Created with IntelliJ IDEA. 
  3.  * User: Administrator 
  4.  * Date: 13-7-3 
  5.  * Time: 上午9:20 
  6.  * To change this template use File | Settings | File Templates. 
  7.  */  
  8. $(document).ready(function () {  
  9.     $("#up1").click(function(){  
  10.         var temp = ["gridDoc","caseDoc"];  
  11.         ajaxFileUpload(temp);  
  12.     });  
  13.   
  14.     $("#addInput").click(function(){  
  15.         addInputFile();  
  16.     });  
  17.   
  18. });  
  19.   
  20. //动态添加一组文件  
  21. function addInputFile(){  
  22.     $("#calculation_model").append(" <tr>"+  
  23.         "<td><input type='file'  name='gridDoc' class='input'></td>   "+  
  24.         "<td><input type='file' name='caseDoc' class='input'></td> "+  
  25.         "</tr>");  
  26. }  
  27.   
  28.   
  29. //直接使用下载下来的文件里的demo代码  
  30. function ajaxFileUpload(id)  
  31. {  
  32.     //starting setting some animation when the ajax starts and completes  
  33.     $("#loading").ajaxStart(function(){  
  34.             $(this).show();  
  35.         }).ajaxComplete(function(){  
  36.             $(this).hide();  
  37.         });  
  38.   
  39.     /* 
  40.      prepareing ajax file upload 
  41.      url: the url of script file handling the uploaded files 
  42.      fileElementId: the file type of input element id and it will be the index of  $_FILES Array() 
  43.      dataType: it support json, xml 
  44.      secureuri:use secure protocol 
  45.      success: call back function when the ajax complete 
  46.      error: callback function when the ajax failed 
  47.  
  48.      */  
  49.     $.ajaxFileUpload({  
  50.             url:'upload.action',  
  51.             //secureuri:false,  
  52.             fileElementId:id,  
  53.             dataType: 'json'  
  54.         }  
  55.     )  
  56.   
  57.     return false;  
  58.   
  59. }  

 我后台是用的struts2,strtus2的上传是比较简单的,只要声明约定的名字,即可得到文件对象,和名称,代码如下:

Java代码   收藏代码
  1. package com.ssy.action;  
  2.   
  3. import com.opensymphony.xwork2.ActionSupport;  
  4. import org.apache.commons.io.FileUtils;  
  5. import org.apache.struts2.util.ServletContextAware;  
  6.   
  7. import javax.servlet.ServletContext;  
  8. import java.io.*;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Date;  
  11. import java.util.Random;  
  12.   
  13. /** 
  14.  * Created with IntelliJ IDEA. 
  15.  * User: Administrator 
  16.  * Date: 13-7-2 
  17.  * Time: 下午4:08 
  18.  * To change this template use File | Settings | File Templates. 
  19.  */  
  20. public class Fileupload extends ActionSupport implements ServletContextAware {  
  21.     private File[] gridDoc,caseDoc;  
  22.     private String[] gridDocFileName,caseDocFileName;  
  23.   
  24.     private ServletContext context;  
  25.   
  26.      
  27.   
  28.     public String execute(){  
  29.         for (int i = 0;i<gridDocFileName.length;i++)    {  
  30.             System.out.println(gridDocFileName[i]);  
  31.         }  
  32.         for (int i = 0;i<caseDocFileName.length;i++)    {  
  33.             System.out.println(caseDocFileName[i]);  
  34.         }  
  35.   
  36.   
  37.         //System.out.println(doc1FileName);  
  38.         //System.out.println(doc2FileName);  
  39.         String targetDirectory = context.getRealPath("/uploadFile");  
  40.   
  41.        /* 
  42.          *这里我只取得  第一组的文件进行上传,第二组的类似 
  43.         */  
  44.  try{  
  45.             for (int i = 0; i < gridDoc.length; i++) {  
  46.                 String targetFileName = generateFileName(gridDocFileName[i]);  
  47.                 File target = new File(targetDirectory, targetFileName);  
  48.                 FileUtils.copyFile(gridDoc[i], target);  
  49.             }  
  50.         }catch (Exception e){  
  51.             e.printStackTrace();  
  52.         }     
  53.   
  54.         return SUCCESS;  
  55.     }  
  56.   
  57.     public File[] getGridDoc() {  
  58.         return gridDoc;  
  59.     }  
  60.   
  61.     public void setGridDoc(File[] gridDoc) {  
  62.         this.gridDoc = gridDoc;  
  63.     }  
  64.   
  65.     public File[] getCaseDoc() {  
  66.         return caseDoc;  
  67.     }  
  68.   
  69.     public void setCaseDoc(File[] caseDoc) {  
  70.         this.caseDoc = caseDoc;  
  71.     }  
  72.   
  73.     public String[] getGridDocFileName() {  
  74.         return gridDocFileName;  
  75.     }  
  76.   
  77.     public void setGridDocFileName(String[] gridDocFileName) {  
  78.         this.gridDocFileName = gridDocFileName;  
  79.     }  
  80.   
  81.     public String[] getCaseDocFileName() {  
  82.         return caseDocFileName;  
  83.     }  
  84.   
  85.     public void setCaseDocFileName(String[] caseDocFileName) {  
  86.         this.caseDocFileName = caseDocFileName;  
  87.     }  
  88.   
  89.     /** 
  90.      * 用日期和随机数格式化文件名避免冲突 
  91.      * @param fileName 
  92.      * @return 
  93.      */  
  94.     private String generateFileName(String fileName) {  
  95.         System.out.println(fileName);  
  96.         SimpleDateFormat sf = new SimpleDateFormat("yyMMddHHmmss");  
  97.         String formatDate = sf.format(new Date());  
  98.         int random = new Random().nextInt(10000);  
  99.         int position = fileName.lastIndexOf(".");  
  100.         String extension = fileName.substring(position);  
  101.         return formatDate + random + extension;  
  102.     }  
  103.   
  104. }  

 写到这里,我就有疑问了,之前的大神改的多文件,为什么还是取id,而且后台是怎么取的,我还是没怎么弄明白,我改的这个代码可行么?是不是存在bug呢?这个还有待考验,如果看出问题,请指出,共同学习

 

最后附上,我修改后的插件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值