Batch upload of Images Using JQuery + ajax (self-writing)

Source: Internet
Author: User

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:
Copy codeThe Code is as follows:
<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:
Copy codeThe Code is as follows:
Var TfileUploadNum = 1; // record the number of Image Selection boxes
Var Tnum = 1; // index when ajax uploads an image
Function TAddFileUpload ()
{
Var idnum = TfileUploadNum + 1;
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:
Copy codeThe Code is as follows:
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:
Copy codeThe Code 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:
Copy codeThe Code is as follows:
Function TajaxFileUpload ()
{
If (Tnum <TfileUploadNum + 1)
{
// Prepare for submission
("# UploadImgState" Upload tnum).html (" ");
// Start submission
. 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] Name of the uploaded file
// StringArray [2] Message prompt
("# UploadImgState" Upload tnum).html (" "); // + stringArray [1] +" | "+ stringArray [2]);
}
Else
{
// Upload Error
("# UploadImgState" effectnum).html ("}
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.
1,
Copy codeThe Code is as follows:
String _ fileNamePath = "";
Try
{
_ FileNamePath = context. Request. Form ["upfile"];
// Start upload
String _ savedFileResult = UpLoadFile (_ fileNamePath );
Context. Response. Write (_ savedFileResult );
}
Catch
{
Context. Response. Write ("0 | error | upload submission error ");
}

2,
Copy codeThe Code is as follows:
// Generate the random file name to be saved
String fileName = GetFileName () + fileNameExt;
// Complete physical path
String toFileFullPath = HttpContext. Current. Server. MapPath (toFilePath );
// Check whether the specified path exists.
If (! Directory. Exists (toFileFullPath ))
{
Directory. CreateDirectory (toFileFullPath );
}
/// Create a WebClient instance
WebClient myWebClient = new WebClient ();
// Set method 1 for windows Network Security Authentication
MyWebClient. Credentials = CredentialCache. DefaultCredentials;
// File to be uploaded
FileStream fs = new FileStream (fileNamePath, FileMode. Open, FileAccess. Read );
// FileStream fs = OpenFile ();
BinaryReader r = new BinaryReader (fs );
// The UploadFile method can be used in the following format
// 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 file is uploaded legally
Copy codeThe Code is as follows:
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 file name to save
Copy codeThe Code is as follows:
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.

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.