jquery+ajax+php image Upload

Source: Internet
Author: User
Tags jquery library jquery file upload
Recently in the writing "online mall" curriculum design, the use of image upload.

I want to achieve the main features are: (1) can upload more than one picture, but of course there are limited, up to 5, (2) to be able to preview the picture, (3) be able to delete the image, (4) The server can obtain the uploaded image information.

From the Internet to find a lot of such code, but not very close to the mind. This evening finally found a, very good, and the explanation is very clear.

The original address: http://www.helloweba.com/view-blog-189.html

The image uploaded here is jquery, which is well compatible with mainstream browsers and is easy to understand and modify. At the same time, this article page solves one of my doubts, is that I see a lot of online is only one input tag can upload pictures, but I do not know how to achieve. But he can only upload a picture here, but as long as a small change can upload more than one picture, specific to their own see it, not much to say, others have explained the details.

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:

      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.

. 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.

 1 $ (function () {2 var bar = $ ('. Bar ');  3 var percent = $ ('. percent ');  4 var showimg = $ (' #showimg ');  5 var progress = $ (". Progress");  6 var files = $ (". Files");  7 var btn = $ (". BTN span"); 8 $ ("#fileupload"). Wrap ("");  $ ("#fileupload"). Change (function () {///Select File $ ("#myupload"). Ajaxsubmit ({dataType: ' json ',                 Data format JSON beforesend:function () {//Start uploading showimg.empty ();//Empty the displayed picture 15 Progress.show (); Show progress bar var percentval = ' 0% '; The starting progress is 0% bar.width (percentval); The width of the progress bar is percent.html (percentval); The display progress is 0% btn.html ("Upload ...");                 Upload button display upload, uploadprogress:function (event, Position, total, percentcomplete) {22 var percentval = percentcomplete + '% '; Progress achieved bar.width (Percentval); Upload progress bar width widened by percent.html (percentval); Show upload progress percent, success:function (data) {///Success 27//Get JSON data returned in background, display file name, size, and Delete button files.html (""+data.name+" ("+data.size+" K)29Delete"); 30//Display the uploaded picture of 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"); 37 Bar.width (' 0 '); Files.html (Xhr.responsetext); Return failure Information 39} 40}); 41}); 42 ... 43});

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.

1 $ (function () {  2     ... Connect the above code  3     $ (". Delimg"). Live (' click ', Function () {  4         var pic = $ (this). attr ("rel");  5         $.post ("Action.php?act=delimg", {imagename:pic},function (msg) {  6             if (msg==1) {  7                 files.html ("delete succeeded.");  8                 Showimg.empty ();//Clear picture  9                 progress.hide ();//Hide Progress bar             }else{                 alert (msg);             13         }); 14     

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.

 1 $action = $_get[' act '];  2 if ($action = = ' delimg ') {//delete picture 3 $filename = $_post[' imagename ');  4 if (!empty ($filename)) {5 unlink (' files/'. $filename);  6 echo ' 1 ';  7}else{8 Echo ' delete failed. ';  9}}else{//upload picture $picname = $_files[' mypic ' [' name ']; $picsize = $_files[' mypic ' [' Size ']; ($picname! = "")          {+ if ($picsize > 512000) {//Limit upload size * The image size cannot exceed 500k '; 17} 18 $type = Strstr ($picname, '. '); Limit upload format if ($type! = ". gif" && $type! = ". jpg") {echo ' picture is not formatted! '; Exit; $rand = rand (100, 999); $pics = Date ("Ymdhis"). $rand. $type; Named image name 25//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, The ' pic ' and $pics, ' size ' and $size 34); echo Json_encode ($arr);  Output JSON data 36}

This article with the use of jquery form plug-in to complete the single-file upload function, in fact, there are many 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. Helloweba will be in the following article in conjunction with examples to explain the multi-file upload and drag-and-drop uploads, as well as the instant upload of images after the cutting and other functions, please pay attention.

  • 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.