search
HomeWeb Front-endJS TutorialHow does ajax's Fileupload implement multiple file uploads?

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);

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); 
}

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

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

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); 
   }); 
  }

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

html:

<p> 
    <img  src="/static/imghwm/default1.png" data-src="scripts/ajaxFileUploader/loading.gif" class="lazy" alt="How does ajax's Fileupload implement multiple file uploads?" > 
    
     </p>
                                                                                                                                                                                      
多组多个文件
第一组第二组
     

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></td> "+ 
  "<td><input></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; 
 
}

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><p style="text-align: left;"> 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 </p>
<p style="text-align: left;">Finally, attached is my modified plug-in</p>
<p style="text-align: left;">ajaxfileupload plug-in</p>
<p>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! </p>
<p>Recommended reading: </p>
<p><a href="http://www.php.cn/js-tutorial-390903.html" target="_blank">Ajax+Servlet to implement non-refresh drop-down linkage (with code)</a><br></p>
<p><a href="http://www.php.cn/js-tutorial-390902.html" target="_blank">How to use Ajax asynchronously Check if the username is duplicate</a><br></p></griddocfilename.length>

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!

Statement
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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.