jquery+php implementation of Ajax file instant upload _php tutorial

Source: Internet
Author: User
Tags jquery file upload
In many projects, you need to use the Instant upload feature, for example, to upload and display images immediately after selecting a local image. This article is a case study of how to use jquery and PHP to implement the Ajax instant upload files, the user simply select the local image to implement the upload, and display the 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.


Next, add the following code to the page:
Copy the Code code as follows:

Add an attachment



0%




We put a BUTTON element in the HTML that adds an attachment. BTN, and progress bar. Progress, the. Files and the #showimg of the display picture for displaying file information
As you can see, the HTML we used to upload the file does not appear in the form form, and the normal upload function depends on the form form. Our form form is dynamically inserted, which avoids multiple forms appearing in a large form.

Css
We use CSS to beautify the form controls of a traditional browse file into a single button, so it doesn't look cool.


Copy CodeThe 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 the various variables, note that the table cell form is dynamically inserted into the Upload button area, and the property enctype of the form must be set to: Multipart/form-data. Then when you click on the "Upload Attachment" button, select the file to upload, call the Jquery.form plug-in Ajaxsubmit method, the following code description.
Copy CodeThe 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 ("");
$ ("#fileupload"). Change (function () {//Select File
$ ("#myupload"). Ajaxsubmit ({
DataType: ' json ',//Data format JSON
Beforesend:function () {//Start uploading
Showimg.empty (); Empty the displayed picture
Progress.show (); Show progress bar
var percentval = ' 0% '; Start Progress is 0%
Bar.width (Percentval); Width of the progress bar
Percent.html (Percentval); Display progress is 0%
Btn.html ("Upload ..."); The upload button shows the crossing
},
Uploadprogress:function (event, Position, total, PercentComplete) {
var percentval = percentcomplete + '% '; Get Progress
Bar.width (Percentval); Upload progress bar width widened
Percent.html (Percentval); Show upload Progress percentage
},
Success:function (data) {//successful
Get JSON data returned in the background, show file name, size, and delete button
Files.html (""+data.name+" ("+data.size+" K)
Delete");
Display the uploaded image
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 plugin, please refer to the form plugin website: http://malsup.com/jquery/form/, the API and various options settings and examples of the form plugin are detailed in the official website.
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.
Copy CodeThe code is as follows:
$ (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 picture
Progress.hide (); Hide Progress bar
}else{
Alert (msg);
}
});
});
});

PHP
You need to process picture uploads and delete images in action.php. Image upload needs to verify the format and size, and then upload the picture through the Move_uploaded_file () method, and finally return the data in JSON format. Deleting a picture uses unlink () to complete the delete operation.
Copy CodeThe code is as follows:
$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 image
$picname = $_files[' mypic ' [' name '];
$picsize = $_files[' mypic ' [' Size '];
if ($picname! = "") {
if ($picsize > 512000) {//Limit upload size
Echo ' image size cannot exceed 500k ';
Exit
}
$type = Strstr ($picname, '. '); Restrict upload format
if ($type! = ". gif" && $type! = ". jpg") {
echo ' picture is not in the right format! ';
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 article with the use of jquery form plug-in to complete the single file upload function, in fact, there are a lot of excellent upload plugin can be used, there are flash-based, jquery-based, typical:jQuery File Upload。 The plugin supports multi-file upload, support drag-and-drop upload, etc., interested students can first understand the next.

http://www.bkjia.com/PHPjc/327662.html www.bkjia.com true http://www.bkjia.com/PHPjc/327662.html techarticle in many projects, you need to use the Instant upload feature, for example, to upload and display images immediately after selecting a local image. This article combines examples to explain how to use jquery and PHP to implement Ajax upload text ...

  • Related Article

    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.