Ajax enables asynchronous file or Image Upload,

Source: Internet
Author: User

Ajax enables asynchronous file or Image Upload,

Hello everyone, I want to share with you the code of the webpage file upload function. I hope you can refer to it or give me some suggestions.

As we all know, all major websites now have file upload functions. Users can store their favorite images or other files on the Internet so that they can easily find them in the future, but how can I set the file upload function of a webpage? Today, I will take Image Upload as an example to show you the specific steps of the file upload function.

In fact, there are two methods for file upload: one is from form submit submission, and the other is ajax Implementation of asynchronous submission, however, a problem with form submission is that the interface will be refreshed every time the upload is complete, and asynchronous upload cannot be implemented. Therefore, almost all websites now use ajax asynchronous upload, now I will show you how to implement ajax asynchronous upload.

First, create a form. The Code is as follows:

<Form action = "" id = "form"> user name: <input type = "text" name = "user"/> </br> password: <input type = "password" name = "pass"/> </br> gender: <input type = "radio" name = "sex" value = "male"/> male <input type = "radio" name = "sex" value = "female"/> female avatar: <input type = "file" id = "file" name = "file"/> </br> <button id = "btn" type = "button"> submit </button> </form> <div class = "con"> </div>

After the image is created, you must first obtain the information of the image uploaded from the current file. The Code is as follows:

Var imgs = []; // store image links // Add the change event var fileM = document for file uploads. querySelector ("# file"); $ ("# file "). on ("change", function () {console. log (fileM. files); // get the file object. files is the property of the file selection control and stores the file object selected by the file selection control. The type is an array var fileObj = fileM. files [0]; // create a formdata object. formData is used to store form data, which is stored in key-value pairs. Var formData = new FormData (); formData. append ('file', fileObj );

The formData here is the object for storing the file information, and then we need to submit it to the background using ajax requests:

// Create the ajax object var ajax = new XMLHttpRequest (); // send the 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) {, // After the upload is successful, the img tag is automatically created and placed in the specified position var img =$ (" "); $ (". con "). append (img); imgs. push (obj. msg);} else {alert (obj. msg );}}}}});

After the request is successful, the backend must process the image and store the image in the specified folder. Therefore, PHP should complete these operations:

<? Php // solve the cross-Origin problem header ("Access-Control-Allow-Origin: *"); // indicates that the data type returned to the foreground is JSONheader ("Content-type: text/json "); // $ _ FILES the hyperglobal variable storage is a file data and an associated array $ fileObj =$ _ FILES ['file']; var_dump ($ fileObj); if ($ fileObj ["error"] = 0) {// determine whether the file is legal $ types = ["jpg", "jpeg ", "png", "gif"]; $ type = explode ("/", $ fileObj ["type"]) [1]; if (in_array ($ type, $ types) {$ time = time (); // get the timestamp and return an integer. // obtain the detailed file 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 moving failed ");}} else {$ infor = array ("err" => 1, "msg" => "invalid file format");} echo json_encode ($ infor);}?>

In this way, we have completed all the steps for uploading files. If you want to upload your favorite images to Your webpage, I hope this code will help you!

Note: If you need to attach other information to the file during file upload, you only need to add this code after the front-end page request is complete:

// Complete form data submission $ ('# btn '). on ('click', function () {// serializeArray () serializes the data in the form control into an array. The array contains several objects, the object contains the name and value var infor =$ ('# form') of the corresponding control '). 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 );}});});

For more highlights, refer to the topic ajax upload Technology Summary.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.