Baidu Multi-file asynchronous upload Control Webuploader basic usage Analysis _jquery

Source: Internet
Author: User
Tags extend file upload int size unique id

Dual-core browser in the Chrome kernel in the use of uploadify always have 302 problems, do not know how to repair, the reason for liking 360 browsers is to help customers control the rendering kernel:

If the page needs to default with the speed core, add tags : <meta name= "renderer" content= "WebKit"/>
if the page need to default with IE compatible kernel, add tags : <meta name= "renderer" content= "Ie-comp"/>
if the page should default to use IE standard kernel, add tags
: <meta name= "renderer" content= "Ie-stand"/>

To solve the 302 problem is also very simple, is HTML5 file upload, just recently in Ueditor to see Baidu's Webuploader, will automatically choose Flash HTML5, is a mature solution.

First look at the front end, we will most commonly used operations encapsulated as plug-ins, asp.net and MVC best use relative to the application absolute path, define the global Applicationpath:var applicationpath = @ (Href ("~") = = " /"?" ": Href (" ~ "))";

Front-End plug-in code:

(Function ($, window) {var Applicationpath = Window.applicationpath = = "" "": Window.applicationpath | | "..
    /..";
    function S4 () {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.360.cn ' > download page </a> ';
   if (window.console) {window.console.log (error);
   } $ (item). text (error);
  Return  var defaults = {hiddeninputid: "Uploadifyhiddeninputid",//Input hidden ID onallcomplete:function (event) { /////When all file is uploaded the callback function Oncomplete:function (event) {},//Each upload a file's callback function Inneroptions: {}, Filenumlimit:unde
 
  Fined, filesizelimit:undefined, filesinglesizelimit:undefined, postbackhold:false};
  var opts = $.extend ({}, defaults, options);
 
  var hdfiledata = $ ("#" + Opts.hiddeninputid); var target = $ (item);//container var Pickerid = "";
  if (typeof guidGenerator36!= ' undefined ')/to a unique id Pickerid = GuidGenerator36 ();
 
  else Pickerid = (((1 + math.random ()) * 0x10000) | 0). toString (+). substring (1); 
   var uploaderstrdiv = ' <div class= "Webuploader" > ' + ' <div id= "thelist" class= "uploader-list" ></div> "+ ' <div class= "btns" > ' + ' <div id= "' + Pickerid + '" > select File </div> ' +//' <a id= ' ctlbtn "class=" b
  TN btn-default "> Start uploading </a> ' + ' </div> ' + ' </div> ';
 
  Target.append (UPLOADERSTRDIV); var $list = target.find (' #thelist '), $btn = Target.find (' #ctlBtn '),//This is reserved so that you can switch at any time to manually upload state = ' pending ', UPL
 
  Oader;
 
  var jsondata = {filelist: []};
 
   var webuploaderoptions = $.extend ({//SWF file path Swf:applicationpath + '/scripts/lib/webuploader/uploader.swf ')
   The File receive service side. Server:applicationpath + '/mvcpages/webuploader/process ',//Select File button.
   Optional.
   The interior is created according to the current run, possibly an INPUT element, or it may be flash. Pick: '# ' + Pickerid,//uncompressed image, default if JPEG, file upload will be compressed before uploading! Resize:false, FileNumLimit:opts.fileNumLimit, FileSizeLimit:opts.fileSizeLimit, FileSingleSizeLimit:opts.file
  Singlesizelimit}, Opts.inneroptions);
 
      var uploader = webuploader.create (webuploaderoptions);
      Restore hiddenfiled on postback when the keep data var filedatastr = Hdfiledata.val (); if (Filedatastr && opts.
      Postbackhold) {jsondata = Json.parse (FILEDATASTR);
      $.each (jsondata.filelist, function (index, filedata) {var newid = S4 ();
      Filedata.queueid = newid; $list. Append (' <div id= ' + newid + ' "class=" item "> ' + ' <div class=" info "> ' + filedata.name + ' </di V> ' + ' <div class= ' state ' > uploaded </div> ' + ' <div class= ' del ' ></div> ' + '
      ;/div> ');
      });
      Hdfiledata.val (Json.stringify (jsondata)); } uploader.on (' filequeued ', function (file) {//queue event $list. Append (' <div id= ' + file.id + ' class= ' item > ' + ' <div class= ' info ' > ' + file.name + ' </div> ' + ' <div class= ' state ' > wait for upload.
  .</div> ' + ' <div class= "del" ></div> ' + ' </div> ');
  });  Uploader.on (' uploadprogress ', function (file, percentage) {//progress bar event var $li = Target.find (' # ' + file.id), $percent =
 
   $li. Find (' progress. Bar '); Avoid repeatedly creating if (! $percent. length) {$percent = $ (' <span class= "Progress" > ' + ' <span class= "percentage" & Gt;<span class= "text" ></span> ' + ' <span class= "bar" role= "ProgressBar" style= "width:0%" > ' + '
   </span></span> ' + ' </span> '). Appendto ($li). Find ('. Bar ');
   $li. Find (' div.state '). Text (' upload ');
   $li. Find (". Text"). Text (Math.Round (percentage * 100) + '% ');
  $percent. css (' width ', percentage * 100 + '% ');
  }); Uploader.on (' uploadsuccess ', function (file, response) {//Upload Success Event Target.find (' # ' + file.id). Find (' div.state '). Text ('
   already uploaded '); var fileevent = {queueId:file.id, Name:file.name, Size:file.size, Type:file.type, FilePath:response.filePath
   };
 
  JsonData.fileList.push (fileevent) opts.oncomplete (fileevent);
 
  });
  Uploader.on (' Uploaderror ', function (file) {target.find (' # ' + file.id). Find (' div.state '). Text (' upload error ');
 
  });
   Uploader.on (' uploadcomplete ', function (file) {//Complete event Target.find (' # ' + file.id). Find ('. Progress '). Fadeout ();
   var fp = $ ("#" + Opts.hiddeninputid);
   Fp.val (Json.stringify (jsondata));
  Opts.onallcomplete (jsondata.filelist);
 
  });
  Uploader.on (' filequeued ', function (file) {uploader.upload ();
 
  });
  Uploader.on (' filesqueued ', function (file) {uploader.upload ();
 
  });
   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 (' suspend upload ');
   else {$btn. Text (' Start uploading ');
 
  }
  });
   $btn. On (' click ', function () {if (state = = ' uploading ') {uploader.stop ();
   else {uploader.upload ();
  }
  });
   Delete $list. On ("click", ". Del", function () {var $ele = $ (this);
   var id = $ele. Parent (). attr ("id");
   var deletefile = {}; $.each (jsondata.filelist, function (index, item) {if (item && Item.queueid = ID) {UPLOADER.R
     Emovefile (Uploader.getfile (ID));//do not omit DeleteFile = JsonData.fileList.splice (index, 1) [0];
     $ ("#" + Opts.hiddeninputid). Val (json.stringify (Jsondata)); $.post (Applicationi + "/webploader/delete", {' Filepathname ': Deletefile.filepath}, Function (Returndata) {$ele. pa
     rent (). remove ();
     });
    Return
  }
   });
 
 });
  } $.fn.powerwebupload = function (options) {var ele = this; if (typeof powerjs!= ' undefined ') {$.lazyload (Applicationpath + "/scripts/lib/webuploader/webuploader.css", function
   () {}, ' CSS ');$.lazyload (Applicationpath + "/scripts/lib/webuploader/webuploader.min.js", function () {initwebupload (ele, Options)
   ;
  });
  else {initwebupload (ele, Options);
 }}) (JQuery, window);

The page introduces the above JS after use:

$ ("#uploader"). Powerwebupload ({hiddeninputid: "Uploadhidden"});

HTML end requires a container and hidden

<div id= "Uploader" ></div>
<asp:hiddenfield id= "Hffilepath" clientidmode= "Static" runat= "Server" /> 

MVC back-end file reception, even if you are asp.net introducing MVC as Ajax is also possible:

Using System;
Using System.Collections.Generic;
Using System.IO;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC; public class Webuploadercontroller:basecontroller {public ActionResult Process (string ID, string name, String type, string lastmodifieddate, int size, httppostedfilebase file) {string filepathname = string.
   empty;string localpath = Path.Combine (Httpruntime.appdomainapppath, "upload\\document");  if (Request.Files.Count = = 0) {return Json (new {JSONRPC = 2.0, error = new {code = 102, message = "Save Failed"}, id =
   "id"});
    try {filepathname =//yourself here to process the file save and return the data that needs to be saved to hidden, files in file or Request.files[0]} catch (Exception) {
   Return Json (New {JSONRPC = 2.0, error = new {code = N, message = "Save Failed"}, id = "id"});
  Return Json (New {JSONRPC = "2.0", id = "id", FilePath = URLPath + "/" + filepathname}); static string URLPath = ". /..

 
  /upload/document "; Public ActionResult Delete (striNg Filepathname) {if (string).
   IsNullOrEmpty (Filepathname)) {return Content ("no");
    //In order to security check the path is not rigorous itself more business to do more detailed judgment if (!filepathname.startswith (URLPath) | | Filepathname.substring (6, filepathname.length-7). Contains ("..
   /") {return Content (" no! "); } string localfilepathname = this.
 
   Server.MapPath (filepathname);
    try {bool b = uploadifymanager.deleteattachment (localfilepathname);
 
    if (!b) throw new Exception ("Delete file failed");
   Return Content ("OK");
   Catch {return Content (' no ');

 }
  }
 }

First page was retired, now re-edited to make the content more complete, optimize the plug-in code

Complete Demo:https://github.com/gxrsprite/aspnetmvcwebuploaderdemo

Add:

Extension of custom parameters, using the Uploadbeforesend event can extend the parameters, the plug-in can be modified as needed.

The issue of cookies, I use Microsoft's own login system, do not need to do any special processing completely no problem.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.