Many projects need to use the real-time upload function, for example, select the local picture, immediately upload and display the image. This article combined with examples to explain how to use jquery and PHP to achieve Ajax real-time upload file function, users simply select the local image after the realization of upload, and display upload progress bar, upload completed, display picture information.
Html
This example is based on jquery and a fairly good jquery.form plug-in, so first load the jquery library and the form plug-in.
The code is as follows |
Copy Code |
<script type= "Text/javascript" src= "Jquery.min.js" ></script> <script type= "Text/javascript" src= "Jquery.form.js" ></script> |
Then add the following code to the page:
code is as follows |
copy code |
<div class= "BTN" > <span> Add attachment </span> <input id= "FileUpload" type= "file" name= "Mypic" >&NBSP; </ DIV>&NBSP <div class= "Progress" >&NBSP; <span class= "Bar" ></span><span class= "percent" >0%</SPAN&NBSP;>&NBSP; </div> <div class= "Files" ></div> <div id= "showimg" ></DIV>&NBSP; |
We place a button element in HTML that adds an attachment. BTN, and the progress bar. Progress, used to display file information. Files and display picture #showimg
As you can see, our HTML for uploading files does not appear in the form form, and the normal upload function relies on form forms. Our form form is inserted dynamically, which prevents multiple forms from appearing in a large form.
Css
We use CSS to beautify the traditional browsing of a file's form controls into a button, which doesn't look cool.
The code is as follows |
Copy Code |
. Btn{position:relative;overflow:hidden;margin-right:4px;display:inline-block; *display:inline;padding:4px 10px 4px;font-size:14px;line-height:18px; *line-height:20px;color: #fff; Text-align:center;vertical-align:middle;cursor:pointer;background: #5bb75b; border:1px solid #cccccc border-color: #e6e6e6 #e6e6e6 #bfbfbf; Border-bottom-color: #b3b3b3;-webkit-border-radius:4px; -moz-border-radius:4px;border-radius:4px;} . btn input{position:absolute;top:0; right:0;margin:0;border:solid Transparent; Opacity:0;filter:alpha (opacity=0); Cursor:pointer;} . progress{position:relative; margin-left:100px; margin-top:-24px; width:200px;padding:1px; border-radius:3px; Display:none} . bar {background-color:green; display:block; width:0%; height:20px; border-radius:3px; } . percent{position:absolute; height:20px; display:inline-block; top:3px; left:2%; Color: #fff} . files{height:22px line-height:22px; margin:10px 0} . delimg{margin-left:20px color: #090; Cursor:pointer} |
Jquery
First define various variables, pay attention to dynamically insert the table cell form into the Upload button site, and the form's property enctype must be set to: Multipart/form-data. Then when you click the "Upload Attachment" button, select the file to upload, call the Jquery.form plug-in Ajaxsubmit method, the following code description.
The code is as follows |
Copy Code |
$ (function () { var bar = $ ('. Bar '); var percent = $ ('. percent '); var showimg = $ (' #showimg '); var progress = $ (". Progress"); var files = $ (". Files"); var btn = $ (". BTN span"); $ ("#fileupload"). Wrap ("<form id= ' myupload ' action= ' action.php ') Method= ' post ' enctype= ' multipart/form-data ' ></form> '); $ ("#fileupload"). Change (function () {//Select File $ ("#myupload"). Ajaxsubmit ({ DataType: ' json ',//data format is JSON Beforesend:function () {//Start uploading Showimg.empty (); Empty the displayed picture Progress.show (); Show progress bar var percentval = ' 0% '; Start progress to 0% Bar.width (Percentval); The width of the progress bar Percent.html (Percentval); Show progress to 0% Btn.html ("Upload ..."); Upload button to show the crosses }, Uploadprogress:function (event, Position, total, PercentComplete) { var percentval = percentcomplete + '% '; Get Progress Bar.width (Percentval); Upload progress bar width widening Percent.html (Percentval); Show upload progress percent }, Success:function (data) {//success Get back the JSON data in the background, display the filename, size, and delete button Files.html ("<b>" +data.name+ "(" +data.size+ "K) </b> <span class= ' delimg ' rel= ' "+data.pic+" ' > Delete </span> '); Show pictures after uploading var img = "http://demo.helloweba.com/upload/files/" +DATA.PIC; Showimg.html ("Btn.html ("Add Attachment"); Upload button Restore }, Error:function (XHR) {//upload failed Btn.html ("Upload failed"); Bar.width (' 0 '); Files.html (Xhr.responsetext); Return failure information } }); }); ... }); |
For more information about the Jquery.form plug-in, see the Form Plug-in website: http://malsup.com/jquery/form/, the website details the form plug-in API and various options settings and examples.
Next, the file upload completes, if the user wants to delete the uploaded file, can write an AJAX POST request to complete the deletion operation.
The code is as follows |
Copy Code |
$ (function () { ... Connect the code above $ (". Delimg"). Live (' click ', function () { var pic = $ (this). attr ("rel"); $.post ("Action.php?act=delimg", {imagename:pic},function (msg) { if (msg==1) { files.html ("delete succeeded."); Showimg.empty (); Empty pictures Progress.hide (); Hide Progress bar }else{ Alert (msg); } }); }); }); |
Php
The action.php needs to handle picture uploads and delete pictures. Image upload needs to verify the format and size, and then through the Move_uploaded_file () method to upload the image, and finally return the JSON format data. Deleting a picture uses unlink () to complete the delete operation.
The code is as follows |
Copy Code |
$action = $_get[' act ']; if ($action = = ' delimg ') {//delete picture $filename = $_post[' imagename ']; if (!empty ($filename)) { Unlink (' files/'. $filename); echo ' 1 '; }else{ Echo ' delete failed. ' } }else{//Upload picture $picname = $_files[' mypic ' [' name ']; $picsize = $_files[' mypic '] [' size ']; if ($picname!= "") { if ($picsize > 512000) {//Limit upload size echo ' picture size cannot exceed 500k '; Exit } $type = Strstr ($picname, '. '); Limit upload Format if ($type!= ". gif" && $type!= ". jpg") { echo ' picture is not well-formed! '; Exit } $rand = rand (100, 999); $pics = Date ("Ymdhis"). $rand. $type; Named Picture name Upload path $pic _path = "files/". $pics; Move_uploaded_file ($_files[' mypic '] [' tmp_name '], $pic _path); } $size = round ($picsize/1024,2); Convert to KB $arr = Array ( ' Name ' => $picname, ' Pic ' => $pics, ' Size ' => $size ); echo Json_encode ($arr); Output JSON data } |
This paper uses the jquery form plug-in to complete the single file upload function