How to upload images asynchronously using Ajax (html,javascript,php)

Source: Internet
Author: User

The first two days of the project need to use the asynchronous upload pictures and display upload progress function, so find a lot of foreign articles, over the mountains to meet a variety of pits, here write an article record.

Html
<form id="fileupload-form">         <input id="fileupload" type="file" name="file" >   </form>

HTML code There's nothing to say, a form form, and a file type of input. Let's look at the JS section.

Javascript
    //Bind the ' Submit ' event. $(' #fileupload-form '). On (' Submit ',( function(e) {E.preventdefault ();//Serialized form       varSerializedata = $ ( This). Serialize ();//var formData = new FormData (this);$( This). Ajaxsubmit ({type:' POST ', url: *yoururl*, DataType:' JSON ', Data:serializedata,//Data:formdata,            //attention!!! ContentType:false, Cache:false, ProcessData:false, Beforesubmit: function() {                    //processing before uploading images}, Uploadprogress: function (event, Position, Total, PercentComplete){                 //Control the progress bar here}, Success: function(){}, Error: function(data){Alert' Error uploading image ');    }        }); }));//Bind file selection event, one select the picture, let ' form ' submit. $("#fileupload"). On ("Change", function() {$( This). Parent (). submit (); });
Php
<?php    //通过$_FILES[]去获取文件    echo‘$_FILES[‘file‘]‘;
The pits encountered:
    • Serializes a form, because it is a file, cannot pass val() , and text() so on, and so on, gets its value, and can only be submitted by serializing the form. Code inside .serialize() , there is another way .FormData() to use to submit, but the experimental process, the beginning of normal, and then an error. On the stackoverflow.com, someone saw the same problem, did not solve, and then gave up.
    • Ordinary ajax is no way or say it is difficult to get upload progress. A plug-in jquery Form Plugin is used here, and the method is simple, ajax the original configuration can be used, and there are a lot of useful features and detailed use of the document. Recommended ~
    • ajaxUpload a picture These three parameters must be configured contentType: false, cache: false, processData:false, .
    • Get the local preview map, which may have browser compatibility issues.
$ ( "#fileupload"  ). Change (function   ()  { if  (this . Files && Span class= "Hljs-keyword" >this . Files[0 ]) {var                    reader = new  filereader (); Reader.onload = function   (e)  { $ ( ' #theImg ' ). attr ( ' src ' ,        E.target.result);   } reader.readasdataurl (this . Files[0 ]); }}
    • The PHP section notes that although Ajax uses the POST method, the background is accepted as long as the files are used $_FILES . You can $_FILES[‘file‘][‘type‘] do security by judging the file format, we're just demonstrating. There are other parameters, such as the tmp_name file path, which name is the filename. After the background is received, you can use it to move_uploaded_file() save the file to the server. There's not much to say here.
Other supplements

In addition, @_w classmate added, do not refresh the page can also be set by form the target property point to a current page hidden iframe to implement. Let that iframe go to refresh the jump page. The jquery Form plugin mentioned above also supports you in this way.
Also recommend a plugin Jquery-iframe-transport

Recommended Reading
    • Uploading-files-with-ajax
    • Image-upload-example
    • Jquery-progress-bar-for-php-ajax-file-upload

javascriptI am a novice, I hope this article can help more people meet the same problem. If the writing is not good or wrong, but also hope that colleagues can be well-intentioned to point out.

If you want to reprint, please specify the source: http://www.w3ctrain.com/2015/07/11/uploading-image-with-ajax/

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How to upload images asynchronously using Ajax (html,javascript,php)

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.