Home > Web Front-end > JS Tutorial > body text

How does ajax's Fileupload implement multiple file uploads?

php中世界最好的语言
Release: 2018-03-30 17:02:54
Original
1420 people have browsed it

This time I will show you how to implement multiple file uploads with ajax's Fileupload, and how to implement multiple file uploads with ajax's Fileupload. What are the precautions? . The following is a practical case. Let's take a look. one time.

Open Google and search for "ajaxFileupload' 'Multiple file upload'. You can find many similar ones, so why should I write them down?
One is to express gratitude for the contributions of the previous masters; the second is a summary of my own knowledge; the third is that I have made changes based on the original ones. I record them here and may help other friends.

Anyone who has used this plug-in knows the basic usage of this plug-in. I will not talk nonsense and go directly to the code.

I need to implement multiple file uploads. The previous method was to define multiple inputs with different IDs, and then put the ajaxfileuplod method in for loop. This method was seen online. , I don’t think it’s very good, but I found it later on the Internet, which is more advanced, and I directly changed the source code (because the author hasn’t updated it for a long time, and it really can’t meet the requirements). Next, let’s see how I changed it.

Quoting the online practice:

1. Look at the code before modification

var oldElement = jQuery('#' + fileElementId); 
var newElement = jQuery(oldElement).clone(); 
jQuery(oldElement).attr('id', fileId); 
jQuery(oldElement).before(newElement); 
jQuery(oldElement).appendTo(form);
Copy after login

It is easy to see that this is to add the input with the id to from. Then to implement multiple file uploads, change it to the following:

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); 
}
Copy after login

After this change, the initialization code will be written like this:

$.ajaxFileUpload({ 
 url:'/ajax.php', 
 fileElementId:['id1','id2']//原先是fileElementId:'id' 只能上传一个 
});
Copy after login

At this point, you can indeed upload multiple files. , but for me, a new problem comes again. With multiple IDs, the files of my interface are not fixed, but are dynamically loaded. So the IDs need to be dynamically generated. I think it is too troublesome. Why not just use the name? Then change the above code to the following:

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); 
   }); 
  }
Copy after login

If you change it this way, you can upload multiple groups of files. Let's see how I apply it.

html:

<p> 
    <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> 
   </p>
Copy after login

js:

/** 
 * Created with IntelliJ IDEA. 
 * User: Administrator 
 * Date: 13-7-3 
 * Time: 上午9:20 
 * To change this template use File | Settings | File Templates. 
 */ 
$(document).ready(function () { 
 $("#up1").click(function(){ 
  var temp = ["gridDoc","caseDoc"]; 
  ajaxFileUpload(temp); 
 }); 
 
 $("#addInput").click(function(){ 
  addInputFile(); 
 }); 
 
}); 
 
//动态添加一组文件 
function addInputFile(){ 
 $("#calculation_model").append(" <tr>"+ 
  "<td><input type=&#39;file&#39; name=&#39;gridDoc&#39; class=&#39;input&#39;></td> "+ 
  "<td><input type=&#39;file&#39; name=&#39;caseDoc&#39; class=&#39;input&#39;></td> "+ 
  "</tr>"); 
} 
 
 
//直接使用下载下来的文件里的demo代码 
function ajaxFileUpload(id) 
{ 
 //starting setting some animation when the ajax starts and completes 
 $("#loading").ajaxStart(function(){ 
   $(this).show(); 
  }).ajaxComplete(function(){ 
   $(this).hide(); 
  }); 
 
 /* 
  prepareing ajax file upload 
  url: the url of script file handling the uploaded files 
  fileElementId: the file type of input element id and it will be the index of $_FILES Array() 
  dataType: it support json, xml 
  secureuri:use secure protocol 
  success: call back function when the ajax complete 
  error: callback function when the ajax failed 
 
  */ 
 $.ajaxFileUpload({ 
   url:'upload.action', 
   //secureuri:false, 
   fileElementId:id, 
   dataType: 'json' 
  } 
 ) 
 
 return false; 
 
}
Copy after login

I use struts2 in the background. The upload of strtus2 is relatively simple. As long as you declare the agreed name, you can get the file object. , and the name, the code is as follows:

package com.ssy.action; 
 
import com.opensymphony.xwork2.ActionSupport; 
import org.apache.commons.io.FileUtils; 
import org.apache.struts2.util.ServletContextAware; 
 
import javax.servlet.ServletContext; 
import java.io.*; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.Random; 
 
/** 
 * Created with IntelliJ IDEA. 
 * User: Administrator 
 * Date: 13-7-2 
 * Time: 下午4:08 
 * To change this template use File | Settings | File Templates. 
 */ 
public class Fileupload extends ActionSupport implements ServletContextAware { 
 private File[] gridDoc,caseDoc; 
 private String[] gridDocFileName,caseDocFileName; 
 
 private ServletContext context; 
 
  
 
 public String execute(){ 
  for (int i = 0;i<gridDocFileName.length;i++) { 
   System.out.println(gridDocFileName[i]); 
  } 
  for (int i = 0;i<caseDocFileName.length;i++) { 
   System.out.println(caseDocFileName[i]); 
  } 
 
 
  //System.out.println(doc1FileName); 
  //System.out.println(doc2FileName); 
  String targetDirectory = context.getRealPath("/uploadFile"); 
 
  /* 
   *这里我只取得 第一组的文件进行上传,第二组的类似 
  */ 
 try{ 
   for (int i = 0; i < gridDoc.length; i++) { 
    String targetFileName = generateFileName(gridDocFileName[i]); 
    File target = new File(targetDirectory, targetFileName); 
    FileUtils.copyFile(gridDoc[i], target); 
   } 
  }catch (Exception e){ 
   e.printStackTrace(); 
  }  
 
  return SUCCESS; 
 } 
 
 public File[] getGridDoc() { 
  return gridDoc; 
 } 
 
 public void setGridDoc(File[] gridDoc) { 
  this.gridDoc = gridDoc; 
 } 
 
 public File[] getCaseDoc() { 
  return caseDoc; 
 } 
 
 public void setCaseDoc(File[] caseDoc) { 
  this.caseDoc = caseDoc; 
 } 
 
 public String[] getGridDocFileName() { 
  return gridDocFileName; 
 } 
 
 public void setGridDocFileName(String[] gridDocFileName) { 
  this.gridDocFileName = gridDocFileName; 
 } 
 
 public String[] getCaseDocFileName() { 
  return caseDocFileName; 
 } 
 
 public void setCaseDocFileName(String[] caseDocFileName) { 
  this.caseDocFileName = caseDocFileName; 
 } 
 
 /** 
  * 用日期和随机数格式化文件名避免冲突 
  * @param fileName 
  * @return 
  */ 
 private String generateFileName(String fileName) { 
  System.out.println(fileName); 
  SimpleDateFormat sf = new SimpleDateFormat("yyMMddHHmmss"); 
  String formatDate = sf.format(new Date()); 
  int random = new Random().nextInt(10000); 
  int position = fileName.lastIndexOf("."); 
  String extension = fileName.substring(position); 
  return formatDate + random + extension; 
 } 
 
}
Copy after login

After writing this, I have questions. Why did the master change multiple files before and still get the ID, and how to get it in the background? I still don’t understand it. , is the code I changed feasible? Is there a bug? This has yet to be tested. If you see any problems, please point them out and learn together

Finally, attached is my modified plug-in

ajaxfileupload plug-in

I believe you will read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Ajax+Servlet to implement non-refresh drop-down linkage (with code)

How to use Ajax asynchronously Check if the username is duplicate

The above is the detailed content of How does ajax's Fileupload implement multiple file uploads?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template