Baidu Webuploader Open source upload Control two times package, thin front-end code (two code to get rid of upload)

Source: Internet
Author: User
Tags unique id


Objective


First of all, I this is the Webuploader open source upload Control two times package, the bottom or webuploader implementation, just for more concise use of him.



Let's introduce Webuploader



Brief introduction:



Webuploader is a simple HTML5-based, flash-supplemented modern file upload component developed by the Baidu Webfe (FEX) team. In the modern browser can give full play to the advantages of HTML5, while not abandoning the mainstream Internet Explorer, the original Flash runtime, compatible with Ie6+,ios 6+, Android 4+. Two sets of runtime, the same call mode, can be used by the user arbitrary choice.



Using large file fragment concurrent upload, greatly improve the efficiency of file upload.



Website address: http://fex.baidu.com/webuploader/



If you are interested in your own play, you can go directly to the official website



Let's start with the main content:





Body


From above we can see that this webuploader function of Baidu is really very powerful, but as with all the upload control, the use of more cumbersome, such as the following:



You need to refer to a whole bunch of related class libraries first,



And then you have to write the HTML.









Then write a lot of JS, such as:


var uploader = webuploader.create ({    //swf file path    swf:base_url + '/js/uploader.swf ',    //File receive server.    server: ' http://webuploader.duapp.com/server/fileupload.php ',    //Select the File button. Optional.    //internal based on the current run is created, either the INPUT element or flash may be.    Pick: ' #picker ',    //uncompressed image, default if it is JPEG, the file will be compressed before uploading!    Resize:false}); Uploader.on (' uploadprogress ', function (file, percentage) {    var $li = $ (' # ' +file.id),        $percent = $li. Find ('. Progress. Progress-bar ');    Avoid repeatedly creating    if (! $percent. Length) {        $percent = $ (' <div class= "Progress progress-striped Active" > ' +          ' <div class= ' Progress-bar "role=" ProgressBar "style=" width:0% "> ' +          ' </div> ' +        ' </div> ') . AppendTo ($li). Find ('. Progress-bar ');    }    $li. Find (' p.state '). Text (' in-upload ');    $percent. css (' width ', percentage * 100 + '% ');}); /.... The following ellipsis, configuration of various parameters and conditions


We don't want all of this!, just two sentences, take care of our upload. The following:


Create a container <div id= "uploader" style= "margin-left:10px" ></div>
$ (function () {        //Render container        $ ("#uploader"). Powerwebupload ({auto:false,filenumlimit:5});    })    function GetFiles1 () {       //Get uploaded file address        var data = $ ("#uploader"). Getfilesaddress ();        Alert (data[0])    }


Simple and quick, the effect is as follows:






I have written the bootstrap style CSS will automatically reference,



Support multi-File upload,



Automatic identification of duplicate files,



Optional automatic upload and manual upload,



Multiple upload controls can be rendered in the page, no conflicts



Then some webuploader-related configuration parameters can be configured directly on their own.



Below we directly on my encapsulated JS small plug-ins (a bit messy, everybody make a look):


(Function ($, window) {var Applicationpath = Window.applicationpath = = = = ""? "": Window.applicationpath | | "..    /..";    function Suijinum () {return ((1 + math.random ()) * 0x10000) | 0). toString (+). substring (1); } function Initwebupload (item, options) {if (! WebUploader.Uploader.support ()) {var error = "Upload control does not support your browser! Try upgrading your Flash version or using the Chrome engine's browser.            <a target= ' _blank ' href= ' http://se..cn ' > download page </a> ";            if (window.console) {window.console.log (error);            } $ (item). text (error);        Return }//create default parameter var defaults = {auto:true, Hiddeninputid: "Uploadifyhiddeninputid",//INP  UT Hidden ID onallcomplete:function (event) {},//callback function executed after all file uploads Oncomplete:function (event) {},//per upload of a file callback function Inneroptions: {}, filenumlimit:undefined,//to verify the total number of files, exceeded is not allowed to join the queue fi lesizelimit:undefined,//Verify that the total file size is out of boundsis not allowed to join the queue.        filesinglesizelimit:undefined,//Verify that the individual file size exceeds the limit and the queue Postbackhold:false} is not allowed;        var opts = $.extend (defaults, options);        var hdfiledata = $ ("#" + Opts.hiddeninputid);        var target = $ (item);//container var Pickerid = "";        if (typeof guidGenerator36! = ' undefined ')//give a unique id Pickerid = GuidGenerator36 ();        else Pickerid = (((1 + math.random ()) * 0x10000) | 0). toString (+). substring (1);              var uploaderstrdiv = ' <div class= ' webuploader ' > ' Debugger if (opts.auto) {uploaderstrdiv =            ' <div id= ' uploadthelist ' class= ' uploader-list ' ></div> ' + ' <div class= ' btns ' > ' + ' <div id= ' + Pickerid + ' "> select File </div> ' + ' </div> '} else {Uplo            Aderstrdiv = ' <div class= ' uploader-list ' ></div> ' + ' <div class= ' btns ' > ' + ' <div id= '+ Pickerid + ' > select File </div> ' + ' <button class= ' webuploadbtn ' > Start upload </button> ' + ' &                         Lt;/div> '} uploaderstrdiv + = ' <div style= ' display:none ' class= ' uploadhiddeninput ' >        </div> ' uploaderstrdiv+= ' </div> ';        Target.append (UPLOADERSTRDIV); var $list = Target.find ('. Uploader-list '), $btn = Target.find ('. webuploadbtn '),//Manual upload button Standby state = ' Pending ', $hiddenInput = Target.find ('.        Uploadhiddeninput '), uploader;        var jsondata = {fileList: []}; var webuploaderoptions = $.extend ({//SWF file path Swf:applicationpath + '/scripts/lib/webuploader/uplo            Ader.swf ',//File receive server. Server: '/home/addfile ', deleteserver: '/home/deletefile ',//Select the File button.            Optional.            The internal is created according to the current run, either the INPUT element or flash. Pick: ' # ' + Pickerid,//Do not compress image, Default if it is JPEG, the file will be compressed before uploading! Resize:false, FileNumLimit:opts.fileNumLimit, FileSizeLimit:opts.fileSizeLimit, Filesi        NgleSizeLimit:opts.fileSingleSizeLimit}, Opts.inneroptions);        var uploader = webuploader.create (webuploaderoptions);        Restore Hiddenfiled's hold data at postback var filedatastr = Hdfiledata.val (); if (Filedatastr && opts.            Postbackhold) {jsondata = Json.parse (FILEDATASTR);                $.each (jsondata.filelist, function (index, fileData) {var newid = suijinum ();                Filedata.queueid = newid; $list. Append (' <div id= ' + newid + ' "class=" item "> ' + ' <div class=" info "> ' + filedata.name + ' </div> ' + ' <div class= "state" > uploaded </div> ' + ' <div class= "del" ></di            V> ' + ' </div> ');            });        Hdfiledata.val (Json.stringify (jsondata));    }    if (Opts.auto) {uploader.on (' filequeued ', function (file) {debugger; $list. Append (' <div id= ' + $ (item) [0].id + file.id + ' class= ' item ' > ' + ' <span class= ' W Ebuploadinfo ">" + file.name + ' </span> ' + ' <span class= "webuploadstate" > Uploading ... </span&                gt; ' + ' <div class= "webuploaddelbtn" > Delete </div><br/> ' + ' </div> ');            Uploader.upload ();        }); } else {Uploader.on (' filequeued ', function (file) {//queue event $list. Append (' <div id= "' + $ (item) [0].id + file.id + ' "class=" item "> ' + ' <span class=" webuploadinfo "> ' + file.name + ' </span > ' + ' <span class= "webuploadstate" > Wait to upload ...</span> ' + ' <div class= '          Webuploaddelbtn "> Delete </div><br/> ' + ' </div> ');  }); } uploader.on (' Uploadprogress ', function (file, percentage) {//progress bar event var $li = Target.fin            D (' # ' + $ (item) [0].id + file.id), $percent = $li. Find ('. Progress. Bar ');                    Avoid repeatedly creating if (! $percent. length) {$percent = $ (' <span class= "Progress" > ' + ' <span class= ' percentage ' ><span class= ' text ' ></span> ' + ' <span class= ' bar ' role = "ProgressBar" style= "width:0%" > ' + ' </span></span> ' + ' </span> '). AP            Pendto ($li). Find ('. Bar ');            } $li. Find (' Span.webuploadstate '). HTML (' in-upload ');            $li. Find (". Text"). Text (Math.Round (percentage * 100) + '% ');        $percent. css (' width ', percentage * 100 + '% ');        }); Uploader.on (' uploadsuccess ', function (file, response) {//Upload Success Event Debugger if (response.state = = "Err or ") {Target.find (' #' + $ (item) [0].id + file.id]. Find (' Span.webuploadstate '). HTML (response.message);                } else {target.find (' # ' + $ (item) [0].id + file.id). Find (' Span.webuploadstate '). html (' uploaded ');  $hiddenInput. Append (' <input type= ' text ' id= ' hiddeninput ' +$ (item) [0].id + file.id + ' class= ' hiddeninput ' value= ' +        Response.message + '/> ')}); Uploader.on (' Uploaderror ', function (file) {target.find (' # ' + $ (item) [0].id + file.id). Find (' Span.webuploadsta        Te '). html (' upload error ');        }); Uploader.on (' uploadcomplete ', function (file) {//Complete event Target.find (' # ' + $ (item) [0].id + file.id). Find ('. progr        Ess '). FadeOut ();        });            Uploader.on (' All ', function (type) {if (type = = = ' Startupload ') {state = ' uploading ';            } else if (type = = = ' Stopupload ') {state = ' paused ';            } else if (type = = = ' uploadfinished ') {state = ' done '; }            if (state = = = ' uploading ') {$btn. Text (' pause upload ');            } else {$btn. Text (' Start upload ');        }        }); method to execute when deleting Uploader.on (' filedequeued ', function (file) {debugger var fullName =            $ ("#hiddenInput" + $ (item) [0].id + file.id). Val ();                    if (fullname!=null) {$.post (Webuploaderoptions.deleteserver, {fullname:fullname}, function (data) {                alert (data.message);            })} $ ("#" + $ (item) [0].id + file.id). Remove ();                    $ ("#hiddenInput" + $ (item) [0].id + file.id). Remove (); })//multi-file Click Upload Method $btn. On (' click ', function () {if (state = = = ' uploading ') {upload            Er.stop ();            } else {uploader.upload ();        }        }); Delete $list. On ("click", ". Webuploaddelbtn", function () {debugger var $ele = $ (this);            var id = $ele. Parent (). attr ("id");            var id = id.replace ($ (item) [0].id, "");            var file = uploader.getfile (ID);        Uploader.removefile (file);    }); } $.fn.        getfilesaddress = function (options) {var ele = $ (this); var filesdata = Ele.find (".        Uploadhiddeninput ");        var filesaddress = [];        Filesdata.find (". Hiddeninput"). each (function () {Filesaddress.push ($ (). Val ());            }) return filesaddress;        } $.fn.powerwebupload = function (options) {var ele = this; if (typeof Webuploader = = ' undefined ') {var casspath = Applicationpath + "/scripts/webuploader/webuploader.css            ";            $ ("<link>"). attr ({rel: "stylesheet", type: "Text/css", Href:casspath}). AppendTo ("Head");            var Jspath = Applicationpath + "/scripts/webuploader/webuploader.min.js";  $.getscript (Jspath). Done (function () {initwebupload (ele, Options);          }). Fail (function () {alert ("Please check that the path to Webuploader is correct!")                   });        } else {initwebupload (ele, Options); }}) (JQuery, window);


Some of the relevant more important parameters are written in comments, we can refer to it.



Then we'll use him.


Introduce JS, remember to first introduce Jquery<script src= "~/scripts/jquery-1.10.2.min.js" ></script><script src= "~/Scripts/ Mywebupload.js "></script>


Write our JS and HTML as follows:


<script>    $ (function () {        $ ("#uploader"). Powerwebupload ({auto:false,filenumlimit:5});    })    function GetFiles1 () {        var data = $ ("#uploader"). Getfilesaddress ();        Alert (data[0])    }</script><div id= "uploader" style= "margin-left:10px" ></div><input type= " Button "value=" 1111 "  onclick=" GetFiles1 () "/>


This will be OK, it is worth noting that



Please refer to the API of the official website for the parameters in Powerwebupload



The Getfilesaddress () method returns an array of file paths after the upload, which is available to you by yourself.
The last one I wrote the demo, using ASP. NET MVC implementation, we download:



Baidu Network Disk:



Link: Http://pan.baidu.com/s/1o8B0xOQ Password: 9KWS



Baidu Webuploader Open source upload Control two times package, thin front-end code (two code to get rid of upload)


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.