Ajax batch upload of Images Using JQuery

Source: Internet
Author: User

 

 

If it is not suitable for the homepage, ask the Administrator to withdraw it early. Thank you!

I searched the internet and found that the code for uploading a single image in jquery + ajax mode is available, but the program for uploading images in batches is not found, so according to the searched code, write a file that can be uploaded in batches.

First look

 

Click the Add button to add a selection box, such:

Select the image to be uploaded as follows:

 

Upload successful, for example:

Let's look at the code below:

Front-end html main code:

 

<Button id = "SubUpload" class = "ManagerButton" onClick = "TSubmitUploadImageFile (); return false; "> confirm upload </button> <button id =" CancelUpload "class =" ManagerButton "onClick =" javascript: history. go (-1); "> cancel </button> <button id =" AddUpload "class =" ManagerButton "onClick =" TAddFileUpload (); return false; "> Add </button> <tr> <td class =" tdClass "> image 1: </td> <td class = "tdClass"> <input name = "" size = "60" id = "uploadImg1" type = "file"/> <span id =" uploadImgState1 "> </span> </td> </tr>

 

 

Because JQuery is used, you can place the click event in the js file.

Add button js Code

Var TfileUploadNum = 1; // record the number of Image Selection boxes var Tnum = 1; // index function TAddFileUpload () {var idnum = TfileUploadNum + 1 when uploading an image via ajax; var str = "<tr> <td class = 'tdclass'> image" + idnum + ": </td> "; str + = "<td class = 'tdclass'> <input name ='' size = '60' id = 'uploadimg "+ idnum +" 'Type = 'file'/> <span id = 'uploadimgstate "+ idnum +" '> "; str + = "</span> </td> </tr>"; $ ("# imgTable "). append (str); TfileUploadNum + = 1;} js Code of the "OK upload" button:

 

Function TSubmitUploadImageFile () {M ("SubUpload "). disabled = true; M ("CancelUpload "). disabled = true; M ("AddUpload "). disabled = true; setTimeout ("TajaxFileUpload ()", 1000); // This is the key code}

 

About setTimeout ("TajaxFileUpload ()", 1000); this code: because of the so-called batch upload, one upload is actually an illusion for the user. We only need to execute TajaxFileUpload () in a delayed manner because I renamed the image in the background when uploading the image to the server. The naming rule is as follows:

Random rd = new Random();StringBuilder serial = new StringBuilder();serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));serial.Append(rd.Next(0, 999999).ToString());return serial.ToString(); 

 

Even if the name is accurate to milliseconds and a random number is added, the second uploaded image overwrites the first uploaded image. So here I set a delay of 1 second before uploading an image. At the beginning, we used a for loop to upload all images one by one using ajax. However, the for loop speed is too fast, maybe the first image has not had time to use ajax, and the second image has been replaced by for, and the second image still overwrites the first image.

 

The following code shows the TajaxFileUpload () function:

 

Function TajaxFileUpload () {if (Tnum <TfileUploadNum + 1) {// prepare to submit for processing $ ("# uploadImgState" +Tnum).html (" "); // start to submit $. ajax ({type: "POST", url: "http: // localhost/ajaxText2/Handler1.ashx", data: {upfile: $ ("# uploadImg" + Tnum ). val (), category: $ ("# pcategory "). val ()}, success: function (data, status) {// alert (data); var stringArray = data. split ("|"); if (stringArray [0] = "1") {// stringArray [0] success status (1 indicates success, 0 indicates failure) // stringArray [1] uploaded file name // stringArray [2] Message prompt $ ("# uploadImgState" required tnum=.html (" "); // + stringArray [1] +" | "+ stringArray [2]);} else {// upload error $ ("# uploadImgState" required tnum).html (" "+ stringArray [2]); // + stringArray [2] +" ") ;}tnum ++; setTimeout (" TSubmitUploadImageFile ()", 0 );}});}}

 

The above code has nothing to say and is easy to understand. Next, let's take a look at how Handler1.ashx (a general handler) processes post images (this code comes from the Internet and the specific address is forgotten). Here we only provide key code, all of which are included in the attachment.

 

String _ fileNamePath = ""; try {_ fileNamePath = context. request. form ["upfile"]; // starts to upload string _ savedFileResult = UpLoadFile (_ fileNamePath); context. response. write (_ savedFileResult);} catch {context. response. write ("0 | error | upload submission error");} 2. // generate the random file name string fileName = GetFileName () + fileNameExt; // physical full path string toFileFullPath = HttpContext. current. server. mapPath (toFilePath); // check whether this path exists. if (! Directory. exists (toFileFullPath) {Directory. createDirectory (toFileFullPath);} // create a WebClient instance WebClient myWebClient = new WebClient (); // set the windows Network Security authentication method 1myWebClient. credentials = CredentialCache. defaultCredentials; // file to be uploaded FileStream fs = new FileStream (fileNamePath, FileMode. open, FileAccess. read); // FileStream fs = OpenFile (); BinaryReader r = new BinaryReader (fs); // you can use the following format to use UploadFile: // myWebClient. uploadFile (toFile, "PUT", fileNamePath); byte [] postArray = r. readBytes (int) fs. length); Stream postStream = myWebClient. openWrite (toFile, "PUT"); if (postStream. canWrite) {postStream. write (postArray, 0, postArray. length);} 3. Check whether the uploaded file private bool CheckFileExt (string _ fileExt) {string [] allowExt = new string [] {". gif ",". jpg ",". jpeg "}; for (int I = 0; I <allowExt. length; I ++) {if (allowExt [I] ==_ fileExt) {return true ;}} return false ;} 4. Generate the public static string GetFileName () {Random rd = new Random (); StringBuilder serial = new StringBuilder (); serial. append (DateTime. now. toString ("yyyyMMddHHmmssff"); serial. append (rd. next (0, 999999 ). toString (); return serial. toString ();}

 

 

OK. Basically, the JQuery + ajax Method for batch uploading images is complete. If you want to upload a Word document or PDF file, you only need to make some modifications.

 

 

PS: N people are allowed to pass this article! I personally think that the posts on the homepage of the blog garden should be those suitable for middle-level programmers and less articles written by N people, because most of the users accessing the blog garden are middle-level programmers. If

Which of the following N Articles can only be read by N people? How many N visits can the blog garden have in a day?

Sorry, I spoke too much today!

This article Reprinted from: http://www.cnblogs.com/Jayan/archive/2009/03/31/1425897.html

 

 

 

 

 

 

 

Related Article

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.