Jquery+ajax realize batch upload picture (write) _ajax related

Source: Internet
Author: User

Search on the Internet, found that the jquery+ajax way to achieve a single picture upload code is some, but to achieve a lot of upload pictures of the program but did not search, so according to the search code, wrote a can bulk upload.
Look at the effect chart first

Clicking on the Add button will add a selection box, as shown below:


Select the picture you want to upload, the effect is as follows:


Upload success as shown below:

Here's a look at the code:
Foreground HTML main code:

Copy Code code 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; " > Increase </button>
<TR><TD class= "Tdclass" >
Picture 1:
</TD><TD class= "Tdclass" >
<input name= "" "Size=" id= "UPLOADIMG1" type= "file"/>
<span id= "UploadImgState1" ></span>
</td></tr>

Because of the jquery, you can put the click event in the JS file.
"Add" button JS code:
Copy Code code as follows:

var tfileuploadnum=1; Record Picture selection box number
var tnum=1; Ajax Upload Image Index
function Taddfileupload ()
{
var idnum = tfileuploadnum+1;
var str= "<tr><td class= ' tdclass ' > Picture" +idnum+ ":</td>";
str = "<td class= ' tdclass ' ><input name= ' ' size= ' id= ' uploadimg '" +idnum+ "' type= '" '/><span ' Uploadimgstate "+idnum+" ' > ';
STR + + "</span></td></tr>";
("#imgTable"). Append (str);
Tfileuploadnum + 1;
}


"OK upload" button JS code:
Copy Code code 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 the so-called bulk upload, in fact, is one of the upload, to the user is only an illusion. The only reason to delay the execution of tajaxfileupload () is because when I upload the picture to the server, I rename the picture in the background, the rule is, the following code:
Copy Code code 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 I named accurate to milliseconds, plus random number, but there is a second upload of images to upload the first picture coverage of the situation. So here I set a delay of 1 seconds after uploading the next picture. When I first started doing this thing, with a for loop, to put all the pictures of a loop to upload with Ajax, but for the loop too fast, perhaps the first picture has not had time to Ajax, the second is for over, or a second cover the first case appears.
Here's a tajaxfileupload () function with the following code:
Copy Code code as follows:

function Tajaxfileupload ()
{
if (tnum<tfileuploadnum+1)
{
Prepare for submission Processing
("#uploadImgState" +tnum). HTML (" ");
Start submitting
. 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 for success, 0 for failure)
STRINGARRAY[1] Upload a successful filename
STRINGARRAY[2] message Prompts
("#uploadImgState" +tnum). HTML (" ");//+stringarray[1]+" | " +STRINGARRAY[2]);
}
Else
{
Upload Error
("#uploadImgState" +tnum). HTML (" "+stringarray[2]);//+stringarray[2]+" ");
}
tnum++;
SetTimeout ("Tsubmituploadimagefile ()", 0);
}
});
}
}

The above code has nothing to say, it's easy to read. below to see HANDLER1.ASHX (General handler) how to handle the post over the picture (this code from the Internet, the specific address forgotten), the following only give the key code, all the code in the attachment.
1,
Copy Code code as follows:

String _filenamepath = "";
Try
{
_filenamepath = context. request.form["Upfile"];
Start uploading
String _savedfileresult = UploadFile (_filenamepath);
Context. Response.Write (_savedfileresult);
}
Catch
{
Context. Response.Write ("0|error| upload submission error");
}

2,
Copy Code code as follows:

Generate the random file name to be saved
String fileName = GetFileName () + Filenameext;
Physical full path
String tofilefullpath = HttpContext.Current.Server.MapPath (Tofilepath);
Check to see if the path is not created
if (! Directory.Exists (Tofilefullpath))
{
Directory.CreateDirectory (Tofilefullpath);
}
Create a WebClient instance
WebClient mywebclient = new WebClient ();
Set Windows network Security authentication Method 1
Mywebclient.credentials = CredentialCache.DefaultCredentials;
Files to upload
FileStream fs = new FileStream (Filenamepath, FileMode.Open, FileAccess.Read);
FileStream fs = OpenFile ();
BinaryReader r = new BinaryReader (FS);
Use the UploadFile method to use 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 legal upload file
Copy Code code 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 be saved
Copy Code code 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 this batch uploads the picture the Jquery+ajax way realizes the procedure completes. If you want to upload a Word document, PDF file, as long as a little change, you can achieve.

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.