Ajax implementation of asynchronous file or image Upload function instance sharing

Source: Internet
Author: User
This article is mainly for you to introduce the AJAX implementation of asynchronous file (image) upload function, with a certain reference value, interested in small partners can refer to, hope to help everyone.

It is well known that the major sites now have a file upload function, users can put their favorite pictures or other files in the online storage, so that later use when convenient to find, but a page of the file upload function how to set it? Today I take pictures upload as an example to show you the file upload function of the specific steps.

In fact, there are two ways to upload a file, one is the from form submit submission, one is the AJAX implementation of asynchronous submission, but the form form submission has a problem is that each time the upload is completed will refresh the interface, can not be implemented asynchronously upload, so now almost all Web sites using Ajax asynchronous upload, Now let me show you how Ajax asynchronous uploads should be implemented.

First, I'll create a form form with the following code:


<form action= "" id= "form" >  user name: <input type= "text" name= "user"/></br>  password: <input type= " Password "name=" pass "/></br>  sex: <input type=" Radio "name=" Sex "value=" male "/> male <input   type=" Radio "name=" Sex "value=" female "/> Female  head: <input type=" file "id=" file "name=" file "/></br>  <button Id= "BTN" type= "button" > Submit </button> </form> <p class= "Con" ></p>

After the creation is completed, first we have to get the user from this upload image information, the code is as follows


var imgs=[];//store Image Link//For file Upload Add Change event var filem=document.queryselector ("#file"); $ ("#file"). On ("Change", function () {  console.log (filem.files);  Gets the file object, files is a property of the file selection control, which stores the file object selected by the file selection control, and the type is an array  var fileobj=filem.files[0];  Creates a Formdata object that formdata the data used to store the form, stored as a key-value pair in the form data.  var formdata=new formData ();  Formdata.append (' file ', fileobj);

The formdata here is the object we want to store the file information for, and then we need to submit it to the backend with an AJAX request:


  Create an Ajax object  var ajax=new xmlhttprequest ();  Send POST request  Ajax.open ("Post", "http://localhost/phpClass/file-upload/move_file.php", true);  Ajax.send (formData);  Ajax.onreadystatechange=function () {  if (ajax.readystate = = 4) {   if (ajax.status>=200 && ajax.status<300| | ajax.status==304) {   console.log (ajax.responsetext);   var obj=json.parse (ajax.responsetext);   alert (obj.msg);   if (Obj.err = = 0) {,    //uploaded successfully after the automatic creation of the IMG tag placed in the specified location    var img =$ (" ");    $ (". Con"). Append (img);    Imgs.push (obj.msg);   } else{    alert (obj.msg);}}}  );

Then after we request the success, the backstage must make the corresponding processing, and saves the picture in the designated folder, therefore the corresponding PHP should complete these actions:


<?php//resolves the cross-domain problem header ("access-control-allow-origin:*");//indicates that the data type returned to the foreground is Jsonheader ("Content-type:text/json");// $_files Super global variable storage is the file data, is an associative array $fileObj =$_files[' file '; Var_dump ($FILEOBJ); if ($FILEOBJ ["Error"]==0) {//Determine if the file is legal $types =["JPG", "JPEG", "PNG", "GIF"]; $type = explode ("/", $FILEOBJ ["type"]) [1]; if (In_array ($type, $types)) {  $time = time ();//gets timestamp returns a reshape  //Get file verbose path  $filePath = "Http://localhost/phpClass/image1". $time. ".". $type;  echo $filePath;  Move the file  $res =move_uploaded_file ($fileObj ["Tmp_name"], "... /image1/". $time.". ". $type);  if ($res) {  $infor =array ("Err" =>0, "msg" = "File moved successfully");  } else{  $infor =array ("Err" =>1, "msg" = "file move Failed");}  } else{  $infor =array ("Err" =>1, "msg" = "file format not valid");} Echo Json_encode ($infor);}? >

So we have completed the file upload all the steps, if you want to put your favorite pictures, upload to your own web page, hope this code can help you!

Attached: If you upload a file with your other information, you only need to complete the front page request after the completion of this code can be implemented:


//completes the submission of the form form data $ (' #btn '). On (' click ', function () {///Serializearray () serializes the data in the form form control to the array,  The array contains several objects that contain the name of the corresponding control and the value var infor = $ (' #form '). Serializearray ();//Console.log (infor);  var stu = {};  for (Var i=0;i<infor.length;i++) {var obj=infor[i];  Stu[obj.name] = Obj.value;  } stu["IMGs"] = IMGs;  stu["IMGs"] = imgs[0];  Send Ajax request $.ajax ({URL: "http://localhost/phpClass/file-upload/data.php", data:{parameter:JSON.stringify (Stu)},  Success:function (res) {console.log (res.msg); }  }); });

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.