AjaxFileupload implements Multifile upload,
Open google search "ajaxFileupload ''multifile upload" and find many similar files. Why should I write it?
I would like to express my gratitude to the previous great gods for their contributions. I would like to summarize my own knowledge. I have changed my original knowledge and recorded it here, which 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 directly go to the code.
I need to upload multiple files. The previous method was to define multiple inputs with different IDs, and then put the ajaxfileuplods METHOD IN THE for loop. This method is displayed on the Internet, I don't think it is very good. I found it on the internet later, so it's a high level. I directly changed the source code (because the author hasn't followed the new one for a long time, and it can't meet the requirements ). Next, let's see how I changed it.
Reference online practices:
1. Check 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 of the id to the from, so to upload multiple files, it will be changed 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 as follows:
$. AjaxFileUpload ({url: '/ajax. php', fileElementId: ['id1', 'id2'] // originally, fileElementId: 'id' can only upload one });
At this point, you can upload multiple files, but for me, there are new problems. There are multiple IDs. The files on my interface are not fixed and are dynamically loaded, I think it is too troublesome to dynamically generate IDS. Why not use the name? Then change the above Code to the following:
If (typeof (fileElementId) = 'string') {fileElementId = [fileElementId];} for (var I in fileElementId) {// var oldElement = jQuery ("input [name =" + fileElementId [I] + "]") by name; oldElement. each (function () {var newElement = jQuery ($ (this )). clone (); jQuery (oldElement ). attr ('id', fileId); jQuery (oldElement ). before (newElement); jQuery (oldElement ). appendTo (form );});}
With this change, you can upload multiple files in multiple groups. Next, let's see how I applied it.
Html:
<Div> <table cellpadding =" 0 "cellspacing =" 0 "class =" tableForm "id =" calculation_model "> <thead> <tr> <th> multiple groups of files </ th> </tr> </thead> <tbody> <tr> <td> group 1 </td> <td> group 2 </td> </tr> <td> <input type = "file" name = "gridDoc" class = "input"> </td> <input type = "file" name = "caseDoc" class = "input"> </td> </tr> </tbody> <tfoot> <tr> <td> <button class = "button" id = "up1"> Upload </button> </td> <button class = "button" id = "addInput"> Add a group </button> </td> </tr> </tfoot> </table> </div>
Js:
/*** Created with IntelliJ IDEA. * User: Administrator * Date: 13-7-3 * Time: am * 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 () ;}); // Add a group of files dynamically. function addInputFile () {$ ("# calculation_model "). append ("<tr>" + "<td> <input type = 'file' name = 'griddoc 'class = 'input'> </td>" + "<td> <input type = 'file' name = 'casedoc' class = 'input'> </td> "+" </tr> ");} // directly use the demo code function ajaxFileUpload (id) {// starting setting some animation when the ajax starts and completes $ ("# loading") in the downloaded file "). 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 and strtus2 for simple uploading. I only need to declare the agreed name to get the file object and 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: * 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");/** here I only obtain the first group of files for upload, and the second group is similar to */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;}/*** use the date and random number to format the file name to avoid conflict * @ 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 ;}}
Here, I have a question: why do I still get the id of multiple files modified by the Old God, and how do I get the id in the background, is the code I changed feasible? Is there a bug? This remains to be tested. If you see the problem, please point out and learn together.
Attached, the modified plug-in
Ajaxfileupload plug-in
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.