Upload control with jquery File upload demo, support multiple upload buttons on the same page

Source: Internet
Author: User
Tags jquery file upload

Demand

There is a need, a form has multiple files to upload, but not the traditional picture batch upload that kind, is similar to this demand, the first is to use the swfupload to do the upload, but the problem is if there are multiple buttons, it is necessary to write a lot of duplicate code, In order to the simplicity of the code so began to seek other methods, during the trial uploadify, but because the style is always not out, and finally gave up, until the discovery of such a small thing, JQuery File Upload.

This article contains upload JS implementation, HTML analysis, CSS implementation and other content, the end of the article has git address

Minimal run time

Official website Download the demo has n many JS files, a large number of JS files only a few is necessary, other files are some of the functions are not used, only when you need to reference.

    <script src= "Http://libs.baidu.com/jquery/1.10.2/jquery.min.js" type= "Text/javascript" ></script>    <script src= "js/jquery/jquery.iframe-transport.js" ></script>    <script src= "js/jquery/ Jquery.ui.widget.js "></script>    <script src=" Js/jquery/jquery.xdr-transport.js "></script >    <script src= "Js/jquery/jquery.fileupload.js" ></script>

Where the iframe file is for the iframe upload, UI file is to be able to select the file automatically upload files necessary, XDR that is required under IE, the last file is the main body

Background code

Create a new ashx file, create a uploadhandler.ashx here, and write the following code to save it.

 public void ProcessRequest (HttpContext context) {context.            Response.ContentType = "Text/plain"; Context.            Response.Charset = "Utf-8"; Httppostedfile file = context.            request.files["Files"]; String uploadpath = HttpContext.Current.Server.MapPath (@context.            request["folder"]) + "\ \"; if (file! = null) {if (!                Directory.Exists (Uploadpath)) {directory.createdirectory (Uploadpath); } file. SaveAs (Uploadpath + file.                FileName); If the following code is missing, the upload queue display will not automatically disappear after uploading successfully. String newName = file.                FileName; String oldname = file.                FileName; Context.            Response.Write ("{\" newname\ ": \" "+ NewName +" \ ", \" oldname\ ": \" "+ oldname +" \ "}"); } else {context.            Response.Write ("0"); }        }

Foreground HTML Preview effect

The final effect as shown, in order to achieve this we step-by-step to analyze.

DIV structure

Such as

    1. As the outermost layer of the entire control
    2. is the button
    3. Is the file name that is displayed when the upload is complete (hidden before upload starts)
    4. Upload progress percentage (hidden before upload starts)
    5. Upload progress bar (hidden before upload starts)

After the 4 div in order to write in the outermost layer, and then consider floating to solve the problem of location, of course, you can also use absolute positioning and other methods to achieve, here selected floating.

Because we need to float, here's a quick explanation of how floating works.

First set the width of 0 is 280px

So the width of the 1 is the 70+margin-right:8 right side and 202 width, left floating

2 width is 150px, left floating

3 width not set, right floating

The width of the 4 is 200+border:2 altogether 202 width, left floats

Then set the Upload button, if you do not set the style, the upload button is like this

This is obviously a cliché, and finding a solution on the internet is like this.

With a style like this

We can do this.

So the HTML code is as follows:

View Code

JS section

The basic upload directly so that it can be,

$ ("Input[type=file]"). FileUpload ();

The uploaded background page is set by the data-url of input, as

The next thing to deal with is upload progress

You can set the bar width by calculating the percentage of uploads.

Here is the built-in Progressall method, passing 2 parameters, the first is E is sender, through he found the trigger input, and then use jquery to find other sibling elements to operate, here is found progress and bar and then set their width

The second parameter is data, which contains two built-in variables, one is total, and the other is loaded, so you can calculate the percentage.

The file name is displayed when the upload is complete, and the hidden input value is assigned.

Using the built-in function Done,done will provide 2 parameters, the first is E is sender, we find the corresponding input through him, and then find other elements to operate

Another parameter is result, which in the comments shows how the result is used

So this is the last JS.

    <script type= "Text/javascript" > Function checkfile (obj) {var array = new Array (' GIF ', ' JPEG ',  ' PNG ', ' jpg ');                The file type that can be uploaded if (Obj.value = = ") {Alert (" Let select the picture to upload! ");            return false; } else {var filecontenttype = Obj.value.match (/^ (. *) (\) (. {1,8}) $/) [3];                This file type is very useful:) var isexists = false;                        for (var i in array) {if (filecontenttype.tolowercase () = = Array[i].tolowercase ()) {                        Isexists = true;                    return true;                    }} if (isexists = = False) {obj.value = null;                    Alert ("The upload image type is incorrect!");                return false;            } return false; }} $ (function () {$ ("input[type=file]"). FileUpload ({done:function (E, result)                   { The Done method is the completed callback function, the other callback functions can view the API//note that the result is to be distinguished from jquery's ajax data parameter, which contains the entire request information                                        The returned data is in Result.result, assuming that our server returned a JSON object//json object {"NewName": "SSS", "Oldname": "SDF"} var Resultjson = $.parsejson (result.result) $ (e.target). attr ("value", Resultjson                    . newName);                    var Uploaddiv = $ (e.target). Parent (). Parent (). parent ();                Uploaddiv.find (". Filestate"). Show (). text (resultjson.oldname);                    }, Progressall:function (e, data) {var maxWidth = 200;                    var percent = (data.loaded/data.total *). toFixed (2);                    var progress = parseint (Data.loaded/data.total * maxWidth, 10);                    var Uploaddiv = $ (e.target). Parent (). Parent (). parent ();                    Uploaddiv.find (". Progress"). Show ();   Uploaddiv.find (". Bar"). CSS ("width", progress);                 Uploaddiv.find (". Progresspercent"). Show (). Text (Percent + "%");        }            })        }); </script>

Git address: https://git.oschina.net/jangojing/jqueryfileuploadDemo.git

Reproduced in: http://www.cnblogs.com/JangoJing/p/4767525.html

Upload control with jquery File upload demo, support multiple upload buttons on the same page

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.