ajaxFileupload多文件上传

简介:

打开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呢?这个还有待考验,如果看出问题,请指出,共同学习



本文转自 www19 51CTO博客,原文链接:http://blog.51cto.com/doujh/1707503,如需转载请自行联系原作者

相关文章
|
4月前
uploadify组件文件上传那些事
uploadify组件文件上传那些事
30 0
|
前端开发 JavaScript
使用ajaxFileUpload实现文件异步上传
使用ajaxFileUpload实现文件异步上传
269 0
|
NoSQL
OkhttpUtils单、多文件上传
OkhttpUtils单文件上传
513 0
|
JavaScript 内存技术 Java
uploadify 实现文件上传
uploadify官网我们需要到官网上下载需要的插件引入到项目中,同时我们最好看看uploadify的中文文档,当然直接把下面的代码复制作为一个工具类也行,反正都是大同小异.
1406 0
|
JavaScript 前端开发
|
Web App开发 JavaScript 数据格式
ajaxfileupload实现文件异步上传
首先需要下载js文件,提供一个CSDN的下载地址 http://download.csdn.
935 0

热门文章

最新文章