JavaScript uses swfupload for multiple file uploads _javascript tips

Source: Internet
Author: User
Tags file info visibility

SWFUpload can be said to be one of the best multiple file upload tools, although it is based on the Flash plug-in development, but compared to the current many JS file upload still has a lot of advantages:

    • Multiple file uploads can be selected at the same time (note that the file is selected)
    • No refresh Upload
    • can display progress bar
    • Good browser compatibility
    • Compatible with other JS class libraries

Another advantage of SWFUpload is its excellent design, which provides a concise set of JavaScript events that developers can use to update the content of the page during file uploads.

The following is the swfupload in the specific use of the JS code
Multifilehandler.js

function Filequeueerror (file, errorcode, message) {try {var imagename = ' error.gif '; 
    var errorname = ""; if (ErrorCode = = swfupload.errorcode_queue_limit_exceeded) {errorname = "file exceeds the maximum number of uploads!" 
    "; 
      } if (ErrorName!== "") {alert (errorname); 
    Return Switch (errorcode) {case Swfupload.queue_error. 
      Zero_byte_file:imagename = "Zerobyte.gif"; 
    Break Case Swfupload.queue_error. 
      File_exceeds_size_limit:imagename = "Toobig.gif"; 
    Break Case Swfupload.queue_error. Zero_byte_file:case Swfupload.queue_error. 
      INVALID_FILETYPE:default:alert (message); 
    Break 
 
  } addimage ("/modules/commons/view/multifileupload/images/" + imagename); 
  catch (ex) {this.debug (ex); 
      } function Filedialogcomplete (numfilesselected, numfilesqueued) {try {if (numfilesqueued > 0) { 
    This.startupload (); The catch (ex) {This.debug (E)x); } function uploadprogress (file, bytesloaded) {try {var percent = Math.ceil ((bytesloaded/file.size) * 1 
 
    00); 
    var progress = new Fileprogress (file, this.customSettings.upload_target); 
    Progress.setprogress (percent); 
      if (percent = =) {if (showthumbnail) {progress.setstatus ("Creating thumbnails ..."); 
      } Progress.togglecancel (False, this); 
      uploadnum++; 
    Setuploadnumber (Uploadnum); 
      else {Progress.setstatus ("is Crossing, completed" +percent+ "%"); 
    Progress.togglecancel (True, this); 
  } catch (ex) {this.debug (ex); 
}//File data sent successfully, regardless of whether it was successfully saved or not, whether the server-side serverdata after the return value///The return value must be success to represent the successful Var servererrorinfo= ""; function uploadsuccess (file, serverdata) {try {var sd=serverdata.replace (//gi, '). Replace (//gi, '). Replace (/\r 
    /gi, '). Replace (/\n/gi, '). Replace (/\t/gi, "); 
      if (showthumbnail) {var filepath= ' ... '; if (savepath!= ') {filepath=filepath+ "/" +savepatH 
      } filepath=filepath+ '/' +file.name; 
    AddImage (FilePath); 
    var progress = new Fileprogress (file, this.customSettings.upload_target); if (showthumbnail) {progress.setstatus ("Thumbnail creation complete!") 
    ");  
        } if (sd!= ') {if (sd!= ' success ') {if (servererrorinfo!= ') {servererrorinfo+= ' <br/> '; 
        } SERVERERRORINFO+=SD; 
      document.getElementById (' Diverror '). Innerhtml=servererrorinfo; 
 
 
  } progress.togglecancel (FALSE); 
  catch (ex) {this.debug (ex); }//Server side return Non-null value to consider upload successful, trigger the following event function uploadcomplete (file) {try {* * I want the next upload to continue AUT 
    omatically so I ' ll call startupload-here/if (This.getstats (). files_queued > 0) {this.startupload (); 
      else {var progress = new Fileprogress (file, this.customSettings.upload_target); 
      Progress.setcomplete (); if (!iscancel) {progress.setstatus ("File Upload success!") 
    ");  }else{progress.setstatus ("Upload has been canceled!") 
        "); 
      Iscancel=false; 
    } progress.togglecancel (FALSE); 
  } catch (ex) {this.debug (ex); 
  } function Uploaderror (file, errorcode, message) {var imagename = "Error.gif"; 
  var progress; try {switch (errorcode) {case Swfupload.upload_error. 
        File_cancelled:try {progress = new fileprogress (file, this.customSettings.upload_target); 
        Progress.setcancelled (); Progress.setstatus ("Cancel complete!") 
        "); 
      Progress.togglecancel (FALSE); 
      catch (Ex1) {this.debug (EX1); 
    } break; Case Swfupload.upload_error. 
        Upload_stopped:try {progress = new fileprogress (file, this.customSettings.upload_target); 
        Progress.setcancelled (); Progress.setstatus ("Stopped!") 
        "); 
      Progress.togglecancel (TRUE); 
      catch (EX2) {this.debug (EX2); Case Swfupload.upload_error. Upload_limit_exceeded:imagename = "Uploadlimit.gif"; 
    Break 
      Default:alert (message); 
    Break 
 
  } addimage ("/modules/commons/view/multifileupload/images/" + imagename); 
  catch (EX3) {this.debug (EX3); 
  } function AddImage (src) {var imagename=getfilename (SRC); 
  var divimage=document.createelement ("span"); 
  DivImage.style.margin = "5px"; 
  divImage.style.padding = "1px"; 
  DivImage.style.width = "59px"; 
  DivImage.style.height = "85px"; 
  divimage.style.display= "Block"; 
  Divimage.style.border= "10px"; 
  Divimage.style.float= "left";  
  Divimage.attachevent ("onmouseover", SetBackground (Divimage, "#FFFACD"));  
   
  Divimage.attachevent ("onmouseout", SetBackground (Divimage, "#FFFFFF")); 
  var newimg = document.createelement ("img"); 
  NewImg.style.margin = "5px"; 
  NewImg.style.width = "59px"; 
  NewImg.style.height = "59px"; 
   
  Newimg.alt=imagename; 
  var divimagename=document.createelement ("div"); Divimagename.style.margintop= "5px"; 
  Divimagename.style.width= "59PX"; 
  Divimagename.style.height= "20px"; 
  divimagename.style.textalign= "center"; 
   
  Divimagename.innerhtml=imagename; 
  Divimage.appendchild (NEWIMG); 
  Divimage.appendchild (Divimagename); 
  document.getElementById ("thumbnails"). AppendChild (Divimage); 
    if (newimg.filters) {try {newImg.filters.item ("DXImageTransform.Microsoft.Alpha"). Opacity = 0; catch (E) {//If It is not set initially, the browser would throw an error. 
      This would set it if it is not set yet. 
    NewImg.style.filter = ' Progid:DXImageTransform.Microsoft.Alpha (opacity= ' + 0 + ') '; 
  } else {newImg.style.opacity = 0; 
  } newimg.onload = function () {fadeIn (newimg, 0); 
  }; 
NEWIMG.SRC = src; 
  function fadeIn (element, opacity) {var reduceopacityby = 5; var rate = 30; 
    FPS if (Opacity <) {opacity + = reduceopacityby; if (Opacity > MB) {opacity = 100; 
    } if (element.filters) {try {element.filters.item ("DXImageTransform.Microsoft.Alpha"). Opaci 
      Ty = opacity; catch (E) {//If It is not set initially, the browser would throw an error. 
        This would set it if it is not set yet. 
      Element.style.filter = ' Progid:DXImageTransform.Microsoft.Alpha (opacity= ' + opacity + ') '; 
    } else {element.style.opacity = opacity/100; 
    } if (opacity < MB) {settimeout (function () {FadeIn (element, opacity); 
  }, rate); } var iscancel=false;//whether to cancel the upload of Var uploadnum=0;//has successfully uploaded the file cancelupload=function () {document.getElementById (' ImgCa 
  Ncelbutton '). style.visible= ' hidden '; 
  Swfu.cancelupload (); 
  /*var fileprogressid = "divfileprogress"; 
  var fileprogresswrapper = document.getElementById (FILEPROGRESSID); 
  var fileprogresselement = Fileprogresswrapper.firstchild; fileprogresselement.childnodes[2].innerhtml = ' upload has stopped! 
'; */iscancel=true; } 
Setuploadnumber=function (num) {document.getElementById ("Lgduploadnumber"). innerhtml= "File Upload (uploaded <span id= ') 
Spnumber ' > ' +num+ "</span> documents"; 
  } getfilename=function (FilePath) {var i=0; 
  if (Filepath.indexof ('/') ==-1) {i=filepath.lastindexof (' \ '); 
  }else{i=filepath.lastindexof ('/'); 
  } var j=filepath.lastindexof ('. '); 
  var filename=filepath.substring (I+1,J); 
return fileName; 
  } setbackground=function (Obj,color) {return function () {setbackgroundwithparams (obj,color); 
  } setbackgroundwithparams=function (Obj,color) {obj.style.backgroundcolor=color; 
  Obj.style.border= "1px"; 
   
Obj.style.bordercolor= "Red"; }/* ****************************************** * Fileprogress Object * Control object for displaying file info * * */function fileprogress (file, targetid) {this.fileprogressid = "Divfilepro 
 
  Gress "; This.fileprogresswrapper = document.getElementById (THIS.FILEPROGRESSID); 
    if (!this.fileprogresswrapper) {this.fileprogresswrapper = document.createelement ("div"); 
    This.fileProgressWrapper.className = "Progresswrapper"; 
 
    This.fileProgressWrapper.id = This.fileprogressid; 
    This.fileprogresselement = document.createelement ("div"); 
 
    This.fileProgressElement.className = "Progresscontainer"; 
    var progresscancel = document.createelement ("a"); 
    Progresscancel.classname = "Progresscancel"; 
    Progresscancel.href = "#"; 
    Progresscancel.id = "Imgcancelbutton";  
    Progresscancel.attachevent ("onclick", cancelupload); 
    progressCancel.style.visibility = "hidden"; 
 
    Progresscancel.appendchild (document.createTextNode ("")); 
    var progresstext = document.createelement ("div"); 
    Progresstext.classname = "Progressname"; 
 
    Progresstext.appendchild (document.createTextNode (file.name)); 
    var ProgressBar = document.createelement ("div"); 
 
    Progressbar.classname = "Progressbarinprogress"; var progresssTatus = document.createelement ("div"); 
    Progressstatus.classname = "Progressbarstatus"; 
 
    progressstatus.innerhtml = ""; 
    This.fileProgressElement.appendChild (Progresscancel); 
    This.fileProgressElement.appendChild (Progresstext); 
    This.fileProgressElement.appendChild (Progressstatus); 
 
    This.fileProgressElement.appendChild (ProgressBar); 
 
    This.fileProgressWrapper.appendChild (this.fileprogresselement); 
    document.getElementById (Targetid). appendchild (This.fileprogresswrapper); 
 
  FadeIn (this.fileprogresswrapper, 0); 
    else {this.fileprogresselement = This.fileProgressWrapper.firstChild; 
  This.fileprogresselement.childnodes[1].firstchild.nodevalue = File.name; 
 
} this.height = This.fileProgressWrapper.offsetHeight;  } FileProgress.prototype.setProgress = function (percentage) {this.fileProgressElement.className = "Progresscontainer 
  Green "; 
  This.fileprogresselement.childnodes[3].classname = "Progressbarinprogress"; This.fileprogresselement.childnodes[3].style.width = percentage + "%"; 
}; 
  FileProgress.prototype.setComplete = function () {this.fileProgressElement.className = "Progresscontainer blue"; 
  This.fileprogresselement.childnodes[3].classname = "Progressbarcomplete"; 
 
This.fileprogresselement.childnodes[3].style.width = ""; 
}; 
  FileProgress.prototype.setError = function () {this.fileProgressElement.className = "Progresscontainer red"; 
  This.fileprogresselement.childnodes[3].classname = "Progressbarerror"; 
 
This.fileprogresselement.childnodes[3].style.width = ""; 
}; 
  FileProgress.prototype.setCancelled = function () {this.fileProgressElement.className = "progresscontainer"; 
  This.fileprogresselement.childnodes[3].classname = "Progressbarerror"; 
 
This.fileprogresselement.childnodes[3].style.width = ""; 
}; 
FileProgress.prototype.setStatus = function (status) {this.fileprogresselement.childnodes[2].innerhtml = status; 
 
}; FileProgress.prototype.toggleCancel= function (show, swfuploadinstance) {this.fileprogresselement.childnodes[0].style.visibility = show? 
  "Visible": "Hidden"; 
    if (swfuploadinstance) {var fileid = This.fileprogressid; 
      This.fileprogresselement.childnodes[0].onclick = function () {swfuploadinstance.cancelupload (FileID); 
    return false; 
  }; 
 } 
};

Multifileupload.js

var uploadurl= ' $! {Request.uploadurl} ';//upload URL for processing var savepath= ' $! 
{Request.savepath} '; var filetype= ' $! 
{Request.filetype} '; 
var postname= ' $request. Postname '; var sizelimit= ' $! 
{request.sizelimit} '; var uploadlimit= ' $! 
{request.uploadlimit} '; var buttonwidth= ' $! 
{request.buttonwidth} '; var buttonheight= ' $! 
{request.buttonheight} '; var buttontext= ' $! 
{Request.buttontext} '; var buttonalign= ' $! 
{request.buttonalign} '; var componentheight= ' $! 
{request.componentheight} '; var showthumbnail= ' $! {Request.showthumbnail} '; Whether to display thumbnails, generally used for picture uploads, default to False var thumbnailscroll= ' $! 
  {request.thumbnailscroll} ';//thumbnail portion shows scroll bar if (uploadurl== ') {//uploadurl= '/commons/fileupload.do '; 
Uploadurl= '/commons/paste.do?template=/multifileupload/data/upload.htm '; 
}//if (Postname= ') {//Postname= "Filedata"; 
} if (filetype== ') {filetype= ' *.* '; 
} if (uploadlimit== ') {uploadlimit=0; 
}//if (buttonwidth== ') {//buttonwidth=100; 
}//if (buttonheight== ') {//buttonheight=22; //}
if (buttontext== ') {buttontext= ' select file '; 
} if (buttonalign== ') {buttonalign= ' left '; 
} if (showthumbnail== ') {showthumbnail=false; 
}else{showthumbnail=true; 
} if (thumbnailscroll== ') {thumbnailscroll=false; 
}else{thumbnailscroll=true; if (Uploadurl.indexof ('? ')! 
=-1) {uploadurl=uploadurl+ ' &savepath= ' +encodeuricomponent (Savepath); 
}else{uploadurl=uploadurl+ '? savepath= ' +encodeuricomponent (Savepath); 
} var swfu; 
    Window.onload = function () {swfu = new SWFUpload ({upload_url:uploadurl, file_size_limit:sizelimit,  File_types:filetype,//file_types_description: "JPG Images", file_upload_limit:uploadlimit,//Zero means 
    Unlimited File_queue_error_handler:filequeueerror, File_dialog_complete_handler:filedialogcomplete, Upload_progress_handler:uploadprogress, Upload_error_handler:uploaderror, UPLOAD_SUCCESS_HANDLER:UPLOADSUC Cess, Upload_complete_handler:uploadcompleTE, Button_image_url: "/modules/commons/view/multifileupload/images/xpbuttonnotext_160x22.png", BUTTON_PLACEH older_id: "Spanbuttonplaceholder", button_width:101, button_height:22, Button_text:buttontext, BU Tton_text_style: '. button {font-family: XXFarEastFont-Arial Xingkai, XXFarEastFont-Franklin Gothic, Sans-serif; font-size:14pt}. buttonsmall {font-size:10pt;} ', Button_text_top_padding:1, button_text_left_padding:20, Flash_url: '/modules/commons/js/swfupload/s 
  Wfupload.swf ", custom_settings: {upload_target:" Divfileprogresscontainer "}, Debug:false 
   
  }); 
    if (thumbnailscroll) {var Divthumbnails=document.getelementbyid ("thumbnails"); 
    var Divcontent=document.getelementbyid ("content"); 
    Divcontent.style.width= "400px"; 
    divthumbnails.style.height= ' 200px '; 
    divthumbnails.style.overflowy= "scroll"; 
  divthumbnails.style.border= "solid 1px #DDF0DD"; } document.getElementById ("Divbuttonplaceholder"). style.tExtalign=buttonalign; 
    if (componentheight!= ') {componentheight=componentheight.replace ("px", ""); Componentheight=number (componentheight) -25;//removes voids and button heights document.getElementById ("Fsprogress"). style.height= 
  componentheight+ "px"; 
 } 
}

Multifilehandler.js is the process of uploading each event, Multifileupload.js is the use of SWFUpload, "$" symbol at the beginning of the actual use of the variable in the process can be customized, in addition to remind everyone here. The Savepath variable in the code is the last saved path to the file, and the background simply reads the variable and saves it to the appropriate location. The following is the background code:

Using System; 
Using System.Data; 
Using System.Configuration; 
Using System.Collections; 
Using System.Web; 
Using System.Web.Security; 
Using System.Web.UI; 
Using System.Web.UI.WebControls; 
Using System.Web.UI.WebControls.WebParts; 
Using System.Web.UI.HtmlControls; 
 
Namespace WebApplication1 
{public 
  partial class FileUpload:System.Web.UI.Page 
  { 
    protected void Page_Load (object sender, EventArgs e) 
    { 
      string path= ""; 
      Httppostedfile file= request.files["Filedata"]; 
      String relationpath=request["Savepath"]; 
      if (relationpath!=string. Empty) 
      { 
        Path=server.mappath ("~/") +relationpath+ "\" +file. FileName; 
      } 
      File. SaveAs (path); 
      Response.Write ("Success");}} 
 

Note that the return value must be given in the background (for example, Response.Write ("Success") in the above code) or swfupload is not considered an upload.

The following actual effect:

Original link: http://blog.csdn.net/jianxin160/article/details/7029207

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.

Related Article

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.