19, Multi-File upload (Ajaxfileupload to achieve multi-file upload function)

Source: Internet
Author: User
Tags call back file handling

From https://www.jb51.net/article/128647.htm

Open Google search "ajaxfileupload" multi-File upload can search a lot of similar, then why do I have to write it?
One is to thank the former great God for his contribution, two are the summary of their own knowledge, three are their own changes on the basis of the original, in this record, may help other friends.

Used this plugin to know the basic usage of this plugin, I will not nonsense, directly on the code.

I need to implement multiple file uploads, the previous practice is to define a number of different IDs of input, and then put the Ajaxfileuplod method in the For loop, this method is seen on the internet, I feel not very good, back online found, on the advanced point, Direct changes to the source (because the author has not been with the new for a long time, but also did not meet the requirements). Now let's see how I changed it.

The practice of quoting the Internet:

1, see no changes in the code before

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 the ID of why the input is added to the from, then to achieve multiple file upload, it will be changed to the following look:

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 ']//was originally Fileelementid: ' id ' can only upload one});

Here, you can upload more than one file, but for me the new problem comes again, multiple IDs, my interface files are not fixed, is dynamic loading, then ID to generate dynamically, I feel too troublesome, why not take the name? Then change the above code to read as follows:

if (typeof (Fileelementid) = = ' String ') {   fileelementid = [Fileelementid];  }  for (var i in Fileelementid) {   //by 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);   });  

This changed so that you can implement multiple sets of file upload, and then see how I applied.

Html:

<div>               <table cellpadding= "0" cellspacing= "0" class= "tableform" id= "Calculation_model" >      <thead>      <tr>       <th> Multiple sets of files </th>      </tr>      </thead>      <tbody>      < Tr>       <td> First group </td>       <td> second group </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" > Add a group </button></td>      </tr>      </tfoot>     </ Table>   </div>

Js:

/** * Created with IntelliJ idea. * User:administrator * date:13-7-3 * Time: Morning 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 ();});  }); Dynamically adds a set of File 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> ");} Use the Demo code function ajaxfileupload (ID) {//starting setting some animation when the Ajax starts and completes $ in the downloaded file ("  #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'll be the index of $_fileS Array () datatype:it support JSON, XML secureuri:use secure protocol Success:call back function when the Ajax compl   Ete error:callback function when the Ajax failed */$.ajaxfileupload ({url: ' upload.action ',//secureuri:false,  Fileelementid:id, DataType: ' JSON '}) return false; }

I use the backstage Struts2,strtus2 upload is relatively simple, as long as the declaration of the name of the contract, you can get the file object, and the name, the code is as follows:

?
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66676869707172737475767778798081828384858687888990919293949596979899100101102103104 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;  }  }

Write here, I have doubts, before the big God changed many files, why still take ID, and backstage is how to take, I still didn't how to understand, I changed this code is feasible? Is there a bug? This is still to be tested, if you look at the problem, please point out, learn together

Finally attached, I modified the plugin

19, Multi-File upload (Ajaxfileupload to achieve multi-file upload function)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.