1. Native Write Ajax implementation Picture preview:
Structure:
<input type= "file" >JavaScript code:<script>document.queryselector (' input '). OnChange =function () {//Create asynchronous object var ajax =new XMLHttpRequest ();// Set the request line Ajax.open (' Post ', './backpreviewimg.php '),//2.0 version can not write the request header//callback function Ajax.onload =function () {Console.log ( Ajax.responsetext)///The return URL directly to the IMG can be document.queryselector (' img '). src = ajax.responsetext;} Set Formdatavar senddata =new FormData ();//You can append senddata.append (' icon ', this.files[0]) without a form form; Set the request Body Ajax.send (senddata); }</script>2. Use jquery for picture previewsThe structure is the same as the native one.JS Code:<script src= ". /js/jquery-1.12.4.min.js "></script><script>$ (function () {///use Ajax to implement picture preview $ (' input '). Change ( function () {var senddata =new FormData ();//When sending data where no required name value can be formdata.append out senddata.append (' icon ', this.files [0]); $.ajax ({url: './upload.php ', Data:senddata,type: ' Post ',//must add these two sentences, or will error Contenttype:false,processdata:false, Success:function (backdata) {///Console.log (Backdata)//////The data returned (is a picture path) set to the IMG SRC attribute $ (' img '). attr (' src ', backdata);})}) </script>The preview structure is the same as abovePHP Code:<?phpheader (' Content-type:text/html;charset=utf-8 ');//Receive what, return what data//Save file Format$fileName =iconv (' utf-8 ', ' GBK ', $_files[' icon ' [' name ']);//Change file pathmove_uploaded_file ($_files[' icon ' [' tmp_name '], './icon/'. $fileName);//Return Dataecho './icon/'. $_files[' icon ' [' name '];?>Create a new file to save the image, Icon
Simple implementation of the picture preview, through the native Ajax and jquery two ways to achieve picture preview, there is a better way to leave a message oh ...