The Upload control demo using jQuery File Upload supports multiple Upload buttons on the same page and jquerydemo

Source: Internet
Author: User

The Upload control demo using jQuery File Upload supports multiple Upload buttons on the same page and jquerydemo
Requirement

There is such a requirement that a form has multiple files to be uploaded, but it is not the traditional batch upload of images. It is similar to this requirement. At the beginning, swfupload was used for uploading, however, the problem is that if there are multiple buttons, you need to write a lot of repeated code. In order to make the code concise, you start to seek other methods. During this period, you tried uploadify, however, since the style cannot be tuned, I finally gave up until I found such a small thing, jQuery File Upload.

 

This article contains the js Implementation of upload, html analysis, css implementation, and so on. The git address is included at the end of the article.

 

Simplest Runtime

The demo downloaded from the official website has more than N js files. Only a few of the many js files are necessary. Other files are useless functions and need to be referenced only when you need them.

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

 

The iframe file is used for iframe upload. The ui file is a required file that can be automatically uploaded after the file is selected. The xdr file is required under ie, And the last file is the subject.

 

Background code

Create a new ashx file. Here, create an uploadHandler. ashx file 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 display of the upload queue will not automatically disappear after the upload is successful. string newName = file. fileName; string oldName = file. fileName; context. response. write ("{\" newName \ ": \" "+ newName +" \ ", \" oldName \ ": \" "+ oldName + "\"}");} else {context. response. write ("0 ");}}

 

 

Foreground HTML Preview

The final result is shown in. To achieve this, we will analyze it step by step.

 

DIV Structure

For example

 

The last four divs are written in the outermost layer in sequence, and then the location problem is solved by floating. Of course, you can also use absolute positioning and other methods. Here, floating is selected.

Because floating is required, here is a brief explanation of the floating principle.

First, set the width of 0 to 280px.

Therefore, the width of 1 is 70 + margin-right: 8, and the right side has a width of 202, floating on the left.

The width of 2 is 150px, floating on the left

The width of 3 is not set, and the right float

The width of 4 is 200 + border: 2, 202 in total, floating on the left

 

Then set the upload button. If no style is set, the upload button is like this.

This is obviously an old style, and I found a solution on the Internet.

With this style

You can make this effect.

The html code is as follows:

<Style> body {padding: 10px}/* upload control */. upload {margin-top: 10px; width: 280px; height: 30px ;}. upload. uploadbtnBox {float: left; height: 30px; width: 70px; margin-right: 8px ;}. upload. progress {height: 4px; line-height: 4px; * zoom: 1; background: # fff; float: left; width: 200px; border: 1px # ccc solid; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: none ;}. upload. filestate {float: left; height: 20px; text-align: left; width: 150px; line-height: 20px; display: none; color: #333; overflow: hidden ;}. upload. progresspercent {float: right; padding-top: 5px; height: 15px; text-align: right; font-size: 9px; line-height: 15px; color: #333 ;}. upload. uploadbtnBox. a-upload {height: 28px; background: #4090c0; border: 1px solid # dddddddd; color: # ffffff; line-height: 28px; padding: 0 6px; font-size: 0.9em; overflow: hidden; display: inline-block; text-decoration: none; * display: inline; * zoom: 1 }. upload. uploadbtnBox. a-upload input {position: absolute; width: 70px; height: 30px; overflow: hidden; margin-left:-10px; opacity: 0; filter: alpha (opacity = 0); cursor: pointer }. upload. progress. bar {height: 4px; line-height: 4px; background: #4090c0; * zoom: 1 ;}. clearfix: after {content :". "; display: block; height: 0; visibility: hidden; clear: both ;}. clearfix {_ zoom: 1 ;}. clearfix {* zoom: 1 ;}</style> <div class = "upload clearfix"> <div class = "uploadbtnBox clearfix"> <a href = "javascript :; "class =" a-upload "> <input type =" file "data-url =" uploadHandler. ashx "name =" files "value =" "id =" file7 "onchange =" CheckFile (this) "/> Click Upload </a> </div> <div class =" filestate "> file name </div> <div class =" progresspercent "> </div> <div class = "progress" style = "height: 4px; "> <div class =" bar "style =" width: 0%; "> </div>View Code

 

 

JS Section

The basic upload is just like this,

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

The uploaded background page is set through the input data-url, as shown in figure

 

Next, we need to handle the upload progress.

You can set the bar width by calculating the upload percentage.

Here, we use the built-in progressall method to pass two parameters. The first one is e, Which Is sender. We can use it to find the triggered input, then, use jquery to find other sibling elements. Here, the progress and bar are found and their width is set.

The second parameter is data, which contains two built-in variables: total and loaded. Therefore, the percentage can be calculated.

 

After the upload is complete, the file name is displayed, and a value is assigned to the hidden input,

The built-in function done is used. done provides two parameters. The first one is e, Which Is sender. We can use it to find the corresponding input and other elements for operations.

The other parameter is result. The comment shows how to use result.

 

So the final js is like this.

<Script type = "text/javascript"> function CheckFile (obj) {var array = new Array ('gif', 'jpeg ', 'png', 'jpg '); // The object type that can be uploaded if (obj. value = '') {alert (" select the image to upload! "); Return false;} else {var fileContentType = obj. value. match (/^ (. *)(\.) (. {}) $/) [3]; // This file type regular expression is 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 callback function after the upload is completed, other callback functions can view the api // note that the result must be distinguished from the ajax data parameter of jquery. This object contains the entire request information // The returned data is in the result. in result, assume that our server returns a json object // json object {"newName": "sss", "oldName": "sdf"} var resultJson = $. parseJSON (result. result) returns (e.tar get ). attr ("value", resultJson. newName); var uploadDiv = iterator (e.tar get ). parent (). parent (). parent (); uploadDiv. find (". filestate "). show (). text (resultJson. oldName) ;}, progressall: function (e, data) {var maxWidth = 200; var percent = (data. loaded/data. total * 100 ). toFixed (2); var progress = parseInt (data. loaded/data. total * maxWidth, 10); var uploadDiv = iterator (e.tar get ). 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

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.