Home  >  Article  >  Backend Development  >  Detailed explanation of jQuery+php to implement instant upload of ajax files_PHP tutorial

Detailed explanation of jQuery+php to implement instant upload of ajax files_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:05:38787browse

The instant upload function is needed in many projects. For example, after selecting a local image, the image is uploaded and displayed immediately. This article uses examples to explain how to use jQuery and PHP to implement the function of Ajax instant file upload. Users only need to select a local image and upload it, and display the upload progress bar. After the upload is completed, the image information is displayed.

查看演示DEMO 下载源码

HTML
This example is based on jQuery and the excellent jquery.form plug-in, so the jquery library and form plug-in must be loaded first.


Then add the following code to the page:

Copy the code The code is as follows:


Add attachment



0%< ;/span >




We place a button element .btn for adding attachments in the html, as well as a progress bar .progress, .files for displaying file information and #showimg for displaying pictures. As you can see, we There is no form in the HTML used to upload files, and the normal upload function relies on the form. Our form is dynamically inserted, which can avoid multiple forms appearing in a large form.

CSS
We use css to beautify the traditional form control for browsing files into a button, doesn’t it look cool?


Copy code The code is as follows:
.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. Note that the form element form is dynamically inserted into the upload button, and the form attribute enctype must be set to: multipart/form-data. Then when you click the "Upload Attachment" button and select the file to be uploaded, call the ajaxSubmit method of the jquery.form plug-in, as explained in the following code.

Copy code The code is as follows:

$(function () {
var bar = $('.bar');
var percent = $('.percent');
var showimg = $('# showimg');
var progress = $(".progress");
var files = $(".files");
var btn = $(".btn span");
$("#fileupload").wrap("
method='post' enctype='multipart/form-data'>
");
$("#fileupload").change(function(){ //Select file
$("#myupload").ajaxSubmit({
dataType: 'json', //data The format is json
                                                                                                                                                                                                                               percentVal = '0%'; //The starting progress is 0%
                                                                                                                                               .html("Uploading..."); //The upload button shows that uploading is in progress. '; //Get progress
bar.width(percentVal); //Upload progress bar width becomes wider
percent.html(percentVal); //Display upload progress percentage
},
success: function(data) { //Success
                                 // Obtain the json data returned from the background, display the file name, size, and delete button data.size+"k)
                                                                                             ​ The picture after
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 Failure");
bar.width('0');
files.html(xhr.responseText); //Return failure message
}
});
});
...
});


For more information about the jquery.form plug-in, please refer to the official website of the form plug-in: http://malsup.com/jquery/form/, official website The API and various option settings and examples of the form plug-in are introduced in detail.
Next, the file upload is completed. If the user wants to delete the uploaded file, he can write an ajax post request to complete the deletion operation.



Copy code

The code is as follows:

$(function () {
...continue the above code
$(".delimg").live('click',function(){
var pic = $ (this).attr("rel");
$.post("action.php?act=delimg",{imagename:pic},function(msg){
if(msg==1){
             files.html("Delete successfully."); 🎜> alert(msg); 🎜>action.php needs to handle image uploading and deletion. When uploading images, you need to verify the format and size, then upload the images through the move_uploaded_file() method, and finally return data in json format. When deleting a picture, use unlink() to complete the deletion operation.



Copy code

The code is as follows:


$action = $_GET['act'];
if($action =='delimg'){ //Delete image
$filename = $_POST['imagename']; if(!empty($filename)){ unlink('files/'.$filename );
           echo '1'; mypic']['name'];
$picsize = $_FILES['mypic']['size'];
if ($picname != "") {
if ($picsize > 512000) { //Limit upload size
                                                                                                                                                                                                                                                           ; if ($ Type! = ".Gif" && $ Type! = ".Jpg") { Echo 'The picture format was wrong! '; exit; }
$rand = rand(100, 999);
$pics = date("YmdHis") . $rand . $type; //Name the picture name
                                                                                                                                                                       = round($picsize/1024,2); //Convert to kb
$arr = array(
'name'=>$picname,
'pic'=>$pics,
'size'=>$size
);
echo json_encode($arr); //Output json data
}


This article is completed with the help of jquery form plug-in For the single file upload function, there are actually many excellent upload plug-ins currently available, some based on flash and some based on jquery. Typical ones are:
jQuery File Upload
. This plug-in supports multiple file uploads, drag-and-drop uploads, etc. Interested students can learn more about it first.





http://www.bkjia.com/PHPjc/327662.html

www.bkjia.com

true

http: //www.bkjia.com/PHPjc/327662.html

TechArticle

Many projects require the instant upload function. For example, after selecting a local image, the image will be uploaded and displayed immediately. This article combines examples to explain how to use jQuery and PHP to implement Ajax instant upload...





Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn