JQuery + php ajax File Upload implementation code

Source: Internet
Author: User
Tags php file upload

Before uploading ajax files, I used js ajax for the most frequently written files. Next I will introduce the implementation code of jQuerya ajax + php File Upload. If you have any need to know about it, please refer.

Real-time upload is required for many projects. For example, you can select a local image to upload and display the image immediately. This document uses examples to illustrate how to use jQuery and PHP to implement the Ajax instant file upload function. You only need to select a local image to complete the upload and display the upload progress bar. After the upload is complete, displays image information.


This example is based on jQuery and excellent jquery. form plug-ins. Therefore, you must first load the jquery library and form plug-ins.

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>

Add the following code to the page:

The Code is as follows: Copy code

<Div class = "btn">
<Span> Add attachments </span>
<Input id = "fileupload" type = "file" name = "mypic">
<Div class = "progress">
<Span class = "bar"> </span> <span class = "percent"> 0% </span>
<Div class = "files"> </div>
<Div id = "showimg"> </div>

We place a button element. btn for adding attachments in html and a progress bar. progress, used to display file information. files and # showimg for displaying images

We can see that the form does not appear in the html used to upload files, and the normal upload function depends on the form. Our form is dynamically inserted to avoid multiple forms in a large form.


We can use css to beautify the Form Controls of traditional browser files into a button, so it looks 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}


First, define various variables. Note that the form Element form must be dynamically inserted to the upload button, and the form attribute enctype must be set to multipart/form-data. Then, click the "Upload attachment" button and select the file to be uploaded. Call the ajaxSubmit method of the jquery. form plug-in. The following Code describes the code.

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 a file
$ ("# Myupload"). ajaxSubmit ({
DataType: 'json', // the data format is json
BeforeSend: function () {// start upload
Showimg. empty (); // clear the displayed Image
Progress. show (); // display the progress bar
Var percentVal = '0% '; // The start progress is 0%.
Bar. width (percentVal); // The width of the progress bar
Percent.html (percentVal); // The display progress is 0%.
Btn.html ("Uploading..."); // the upload button is being uploaded.
UploadProgress: function (event, position, total, percentComplete ){
Var percentVal = percentComplete + '%'; // get the progress
Bar. width (percentVal); // width of the upload progress bar
Percent.html (percentVal); // displays the upload progress percentage.
Success: function (data) {// success
// Obtain the json data returned by the background, display the file name, size, and delete button
Files.html ("<B>" + data. name + "(" + data. size + "k) </B>
<Span class = 'delimiter' rel = '"+ data. pic +"'> Delete </span> ");
// Display the uploaded Image
Var img = "http://demo.helloweba.com/upload/files/" + data. pic;
Showimg.html (" ");
Btn.html ("add attachment"); // upload button to restore
Error: function (xhr) {// Upload Failed
Btn.html ("Upload Failed ");
Bar. width ('0 ');
Files.html (xhr. responseText); // returns the error message.

For more information about the jquery. form plug-in, refer to the official website of the form plug-in: http://malsup.com/jquery/form/. the official website details the apiof the form plug-in and the various types of settings for example.

Next, the file upload is complete. If you want to delete the uploaded file, you can write an ajax post request to complete the deletion operation.

The Code is as follows: Copy code

$ (Function (){
... Connect to the following code
$ (". Delimg"). live ('click', function (){
Var pic = $ (this). attr ("rel ");
$. Post ("action. php? Act = delimg ", {imagename: pic}, function (msg ){
If (msg = 1 ){
Files.html ("deleted successfully .");
Showimg. empty (); // clear the image
Progress. hide (); // hide the progress bar
} Else {
Alert (msg );


In action. php, you need to process and delete images. When uploading an image, you must verify the format and size. Then, use the move_uploaded_file () method to upload the image and return the json data. You can use unlink () to delete an image.

The Code is as follows: Copy code

$ Action = $ _ GET ['ac'];
If ($ action = 'delimiter') {// delete an image
$ Filename = $ _ POST ['imagename'];
If (! Empty ($ filename )){
Unlink ('files/'. $ filename );
Echo '1 ';
} Else {
Echo 'deletion failed .';
} Else {// upload an image
$ Picname = $ _ FILES ['mypic '] ['name'];
$ Picsize = $ _ FILES ['mypic '] ['SIZE'];
If ($ picname! = ""){
If ($ picsize> 512000) {// restrict the upload size
Echo 'image size cannot exceed 500k ';
$ Type = strstr ($ picname, '.'); // restrict the upload format
If ($ type! = ". Gif" & $ type! = ". Jpg "){
Echo 'the image format is incorrect! ';
$ Rand = rand (100,999 );
$ Pics = date ("YmdHis"). $ rand. $ type; // name the image
// Upload path
$ Pic_path = "files/". $ pics;
Move_uploaded_file ($ _ FILES ['mypic '] ['tmp _ name'], $ pic_path );
$ Size = round ($ picsize/, 2); // convert to kb
$ Arr = array (
'Name' => $ picname,
'Pic '=> $ pics,
'SIZE' => $ size
Echo json_encode ($ arr); // output json data

This document uses the jquery form plug-in to complete the single file upload function

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.