This article is mainly for you to introduce the Php+ajax implementation of asynchronous upload file or image function, with a certain reference value, interested in small partners can refer to
This article for you to share the Ajax asynchronous upload file or image features of the specific code for your reference, the specific content as follows
HTML code <form enctype= "Multipart/form-data" id= "Upform" > <input type= "file" name= "file" ><br>< br> <input type= "button" value= "Submit" ></form><p class= "Picdis" > </p >
JS code (': Button '). Click (Function (event) {//formdata) to store the asynchronous upload data var formData = new FormData ($ (' form ') [0]); Formdata.append (' file ', $ (': File ') [0].files[0]); Pit point: No matter how the data is transmitted, Console.log (FormData) will appear empty, but in fact the value is present, F12 view NET tab can see the data is uploaded $.ajax ({ URL: ' formtest.php ', Type: ' POST ', data:formdata, //These two settings are required Contenttype:false, processdata:false, success: function (data) { console.log (data) var srcpath = data; Console.log (); Note that the path here is set to $ ('. Picdis img ') based on the path of your own saved files . attr (' src ', ' ... ') +srcpath); } }) });
Php:
<?php $upFile = $_files[' file '];/*** Create folder function to create a folder for saving files * @param str $dirPath folder name * @return Str $dirPath folder name */funct Ion Creadir ($dirPath) {$curPath = DirName (__file__); $path = $curPath. ' \ \ '. $dirPath; if (Is_dir ($path) | | mkdir ($PATH, 0777,true)) { return $dirPath;}} Determine if the file is empty or error if ($upFile [' Error ']==0 &&!empty ($upFile)} {$dirpath = Creadir (' upload '); $filename = $_files[' File ' [' Name ']; $queryPath = './'. $dirpath. ' /'. $filename; Move_uploaded_file to transfer the browser cache file to the server folder if (move_uploaded_file ($_files[' file ' [' Tmp_name '], $queryPath)) { Echo $queryPath; }}?>
After clicking Upload image and sending it, you can see the picture on the page and see the local folder to see that the file has also been saved to the server.
The key to implementing asynchronous uploads at the client is FormData, which is described in more detail here: FormData ()