Implementation Code of jquery batch upload of images

Source: Internet
Author: User

Foreground: upload.htm
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> upload </title>
<Link href = "upload.css" rel = "Stylesheet"/>
</Head>
<Body>
<Form>
<Ul>
<Li>
<Button id = "SubUpload" 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>
</Li>
</Ul>
<Ul id = "loadimage">
<Li>
<Div class = "imagelabel">
Figure 1: </div>
<Div class = "imagepath">
<Input name = "" size = "45" id = "uploadImg1" type = "file"/> </div>
<Div class = "loadinfo">
<Span id = "uploadImgState1"> </span>
</Div>
</Li>
</Ul>
</Form>
</Body>
</Html>
<Script type = "text/javascript" src = "http://www.cnblogs.com/JS/jquery-1.3.2-vsdoc.js"> </script>
<Script type = "text/javascript">
Var TfileUploadNum = 1; // record the number of Image Selection boxes
Var Tnum = 1; // index when ajax uploads an image
// Add upload button
Function TAddFileUpload (){
Var idnum = TfileUploadNum + 1;
Var str = "<li> ";
Str + = "<div class = 'imagelabel '> image" + idnum + ": </div> ";
Str + = "<div class = 'ImagePath'> <input name = ''size = '45' id = 'uploadimg" + idnum + "'Type = 'file'/> </div> ";
Str + = "<div class = 'loadinfo'> <span id = 'uploadimgstate" + idnum + "'> </span> </div> ";
Str + = "</li> ";
$ ("# Loadimage"). append (str );
TfileUploadNum + = 1;
}
// Start upload
Function TSubmitUploadImageFile (){
Document. getElementById ("SubUpload"). disabled = true;
Document. getElementById ("CancelUpload"). disabled = true;
Document. getElementById ("AddUpload"). disabled = true;
SetTimeout ("TajaxFileUpload ()", 1000); // This is the key code
}
// Ajax upload Method
Function TajaxFileUpload (){
If (Tnum <TfileUploadNum + 1 ){
// Prepare for submission
$ ("# UploadImgState" + Tnum).html (" ");
// Start submission
$. Ajax ({
Type: "POST ",
Url: "Handler. ashx ",
Data: {upfile: $ ("# uploadImg" + Tnum). val ()},
Success: function (data, status ){
Var stringArray = data. split ("| ");
// StringArray [0] success status (1 indicates success, 0 indicates failure)
// StringArray [1] Name of the uploaded file
// StringArray [2] Message prompt
If (stringArray [0] = "1 "){
// Upload successful
$ ("# UploadImgState" + Tnum).html ("}
Else {
// Upload Error
$ ("# UploadImgState" + Tnum).html ("}
Tnum ++;
SetTimeout ("TajaxFileUpload ()", 1000 );
}
});
}
Else {
Document. getElementById ("SubUpload"). disabled = false;
Document. getElementById ("CancelUpload"). disabled = false;
Document. getElementById ("AddUpload"). disabled = false;
}
}
</Script>

Handler. ashx
Copy codeThe Code is as follows:
<% @ WebHandler Language = "C #" Class = "Handler" %>
Using System;
Using System. Web;
Using System. IO;
Using System. Text;
Using System. Net;
Public class Handler: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
// Source image path
String _ fileNamePath = "";
Try
{
_ FileNamePath = context. Request. Form ["upfile"];
String _ savedFileResult = UpLoadFile (_ fileNamePath); // start upload
Context. Response. Write (_ savedFileResult); // return the upload result
}
Catch
{
Context. Response. Write ("0 | error | file path error ");
}
}
/// <Summary>
/// Save the image
/// </Summary>
/// <Param name = "fileNamePath"> </param>
/// <Returns> </returns>
Private string UpLoadFile (string fileNamePath)
{
// Image format
String fileNameExt = fileNamePath. Substring (fileNamePath. IndexOf ('.'). ToLower ();
If (! CheckFileExt (fileNameExt) return "0 | error | the image format is incorrect! ";
// Save path
String toFilePath = "ProductUpload /";
// Complete physical path
String toFileFullPath = HttpContext. Current. Server. MapPath (toFilePath );
// Check whether the specified path exists.
If (! Directory. Exists (toFileFullPath ))
{
Directory. CreateDirectory (toFileFullPath );
}
// Generate the random file name to be saved
String toFileName = GetFileName ();
// Complete path to be saved
String saveFile = toFileFullPath + toFileName + fileNameExt;
/// Create a WebClient instance
WebClient myWebClient = new WebClient ();
// Set windows Network Security Authentication
MyWebClient. Credentials = CredentialCache. DefaultCredentials;
// File to be uploaded
FileStream fs = new FileStream (fileNamePath, FileMode. Open, FileAccess. Read );
BinaryReader r = new BinaryReader (fs );
// The UploadFile method can be used in the following format
MyWebClient. UploadFile (saveFile, fileNamePath );
Return "1 |" + toFileName + fileNameExt + "| saved successfully .";
}
/// <Summary>
/// Check the image type
/// </Summary>
/// <Param name = "_ fileExt"> </param>
/// <Returns> return True </returns>
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;
}
/// <Summary>
/// Obtain the random image name
/// </Summary>
/// <Returns> </returns>
Public static string GetFileName ()
{
Random rd = new Random ();
StringBuilder serial = new StringBuilder ();
Serial. Append (DateTime. Now. ToString ("yyMMddHHmmssff "));
Serial. Append (rd. Next (0, 9999). ToString ());
Return serial. ToString ();
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}

CSS style upload.css
Copy codeThe Code is as follows:
Body {font-size: 12pt ;}
Ul {list-style: none ;}
Li {margin: 0px ;}
# Loadimage {width: 860px; overflow: hidden ;}
. Imagelabel {float: left; width: 60px; height: 25px ;}
. Imagepath {float: left; width: 400px; height: 25px ;}
. Loadinfo {float: left; width: 400px; height: 25px ;}

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.