熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C#用jquery多個文件上傳

2022-06-13   來源: .NET編程 

   <%@ Page Language=C# AutoEventWireup=true CodeBehind=Defaultaspxcs Inherits=UploadFile_Default %>

  

   <!DOCTYPE html PUBLIC //WC//DTD XHTML Transitional//EN transitionaldtd>

  

   <html xmlns= >

   <head runat=server>

       <title>Upload Multiple Files in ASPNET Using jQuery</title>

           <script src=Scripts/jqueryjs type=text/javascript></script>

           <script src=Scripts/jqueryMultiFilejs type=text/javascript></script>

   </head>

   <body>

       <form id=form runat=server>

       <div>

           <asp:TextBox ID=TextBox runat=server Height=px TextMode=MultiLine></asp:TextBox>

           <asp:FileUpload ID=FileUpload runat=server CssClass=multi /><asp:Button ID=btnUpload runat=server Text=Upload onclick=btnUpload_Click />

       </div>

  

       </form>

   </body>

   </html>

  服務器端代碼

   using System;

   using SystemData;

   using SystemConfiguration;

   using SystemCollections;

   using SystemWeb;

   using SystemWebSecurity;

   using SystemWebUI;

   using SystemWebUIWebControls;

   using SystemWebUIWebControlsWebParts;

   using SystemWebUIHtmlControls;

   using SystemIO;

  

   namespace UploadFile

   {

       /// <summary>

       /// 多個文件上傳

       /// 塗聚文 QQ: 

       /// </summary>

       public partial class _Default : SystemWebUIPage

       {

  

           string fi;

           protected void Page_Load(object sender EventArgs e)

           {

  

           }

           /// <summary>

           ///

           /// </summary>

           /// <param name=sender></param>

           /// <param name=e></param>

           protected void btnUpload_Click(object sender EventArgs e)

           {

               try

               {

                   //多個文件

  

                   // Get the HttpFileCollection

                   HttpFileCollection hfc = RequestFiles;

                   for (int i = ; i < hfcCount; i++)

                   {

  

                       HttpPostedFile hpf = hfc[i];

                       if (hpfContentLength > )

                       {

                           string name=SystemIOPathGetFileName(hpfFileName);

                           if (nameContains())

                           {

                               SystemRandom srd = new Random();

                               int srdName = srdNext();

                               name = nameSubstring(nameLastIndexOf() nameLength nameLastIndexOf());

                               name = DateTimeNowToString(yyyyMMddhhmmss) + srdNameToString() + name;

                           }

                          // FileUploadPostedFileSaveAs(ServerMapPath(upimge/) + name);

                           if (hfcCount == )

                           {

                               fi = name;

                           }

                           if (hfcCount!= )

                           {

                               //file += name;

                               fi += name+;;

                           }

                           //創造年日的文件夾

                           //string year = DateTimeNowYearToString();

                           //string month = DateTimeNowMonthToString();

                           //string day = DateTimeNowDayToString();

                           //if (DirectoryExists(upload + \\ + year) == false)

                           //{

                           //    DirectoryCreateDirectory(upload + \\ + year);

                           //}

                           //if (DirectoryExists(upload + \\ + year + \\ + month) == false)

                           //{

                           //    DirectoryCreateDirectory(upload + \\ + year + \\ + month);

                           //}

                           //if (DirectoryExists(upload + \\ + year + \\ + month + \\ + day) == false)

                           //{

                           //    DirectoryCreateDirectory(upload + \\ + year + \\ + month + \\ + day);

                           //}

                           //保存地址thisTextBoxText =/ + year + / + month + / + day +/+name;

                           hpfSaveAs(ServerMapPath(upload) + \\ + name);

                           //hpfSaveAs(ServerMapPath(upload) + \\ + SystemIOPathGetFileName(hpfFileName));

                          // ResponseWrite(<b>File: </b> + hpfFileName +   <b>Size:</b> +

                               //hpfContentLength +   <b>Type:</b> + hpfContentType + Uploaded Successfully <br/>);

                       }

                       thisTextBoxText = fi;

                   }

  

               }

               catch (Exception ex)

               {

  

               }

           }

           /// <summary>

           ///

           /// </summary>

           /// <param name=jsContent></param>

           //protected void WriteJs(string jsContent)

           //{

  

           //    ClientScriptRegisterStartupScript(thisGetType() writejs <script type=text/javascript> + jsContent + </script>);

           //}

  

  

       }

   }

  jqueryMultiFilejs代碼

   /*

    ### jQuery Multiple File Upload Plugin v ###

    * Home: fileupload/

    * Code: multifileplugin/

    *

    * Dual licensed under the MIT and GPL licenses:

    *   licensephp

    *  

    ###

   */

  

   /*# AVOID COLLISIONS #*/

   ;if(windowjQuery) (function($){

   /*# AVOID COLLISIONS #*/

  

       // plugin initialization

       $fnMultiFile = function(options){

           if(thislength==) return this; // quick fail

  

           // Handle API methods

           if(typeof arguments[]==string){

               // Perform API methods on individual elements

               if(thislength>){

                   var args = arguments;

                   return thiseach(function(){

                       $fnMultiFileapply($(this) args);

       });

               };

               // Invoke API method handler

               $fnMultiFile[arguments[]]apply(this $makeArray(arguments)slice() || []);

               // Quick exit

               return this;

           };

  

           // Initialize options for this call

           var options = $extend(

               {}/* new object */

               $fnMultiFileoptions/* default options */

               options || {} /* justintime options */

           );

  

           // Empty Element Fix!!!

           // this code will automatically intercept native form submissions

           // and disable empty file elements

           $(form)

           not(MultiFileintercepted)

           addClass(MultiFileintercepted)

           submit($fnMultiFiledisableEmpty);

  

           //###

           // utility method to integrate this plugin with others

           if($fnMultiFileoptionsautoIntercept){

               $fnMultiFileintercept( $fnMultiFileoptionsautoIntercept /* array of methods to intercept */ );

               $fnMultiFileoptionsautoIntercept = null; /* only run this once */

           };

  

           // loop through each matched element

           this

            not(MultiFileapplied)

               addClass(MultiFileapplied)

           each(function(){

               //#####################################################################

               // MAIN PLUGIN FUNCTIONALITY START

               //#####################################################################

  

          // BUG FIX:

          // variable group_count would repeat itself on multiple calls to the plugin

          // this would cause a conflict with multiple elements

          // changes scope of variable to global so id will be unique over n calls

          windowMultiFile = (windowMultiFile || ) + ;

          var group_count = windowMultiFile;

  

          // Copy parent attributes Thanks to Jonas Wagner

          // we will use this one to create new input elements

          var MultiFile = {e:this E:$(this) clone:$(this)clone()};

  

          //===

  

          //# USE CONFIGURATION

          if(typeof options==number) options = {max:options};

          var o = $extend({}

           $fnMultiFileoptions

           options || {}

                          (tadata? tadata(): (ta?MultiFileEdata():null)) || {} /* metadata options */

                                   {} /* internals */

          );

          // limit number of files that can be selected?

          if(!(omax>) /*IsNull(MultiFilemax)*/){

           omax = MultiFileEattr(maxlength);

           if(!(omax>) /*IsNull(MultiFilemax)*/){

            omax = (String(MultiFileeclassNamematch(/\b(max|limit)\([]+)\b/gi) || [])match(/[]+/gi) || [])[];

            if(!(omax>)) omax = ;

            else           omax = String(omax)match(/[]+/gi)[];

           }

          };

          omax = new Number(omax);

          // limit extensions?

          oaccept = oaccept || MultiFileEattr(accept) || ;

          if(!oaccept){

           oaccept = (MultiFileeclassNamematch(/\b(accept\[\w\|]+)\b/gi)) || ;

           oaccept = new String(oaccept)replace(/^(accept|ext)\/i);

          };

  

          //===

  

          // APPLY CONFIGURATION

                               $extend(MultiFile o || {});

          MultiFileSTRING = $extend({}$fnMultiFileoptionsSTRINGMultiFileSTRING);

  

          //===

  

          //#########################################

          // PRIVATE PROPERTIES/METHODS

          $extend(MultiFile {

           n: // How many elements are currently selected?

           slaves: [] files: []

           instanceKey: MultiFileeid || MultiFile+String(group_count) // Instance Key?

           generateID: function(z){ return MultiFileinstanceKey + (z> ?_F+String(z):); }

           trigger: function(event element){

            var handler = MultiFile[event] value = $(element)attr(value);

            if(handler){

             var returnValue = handler(element value MultiFile);

             if( returnValue!=null ) return returnValue;

            }

            return true;

           }

          });

  

          //===

  

          // Setup dynamic regular expression for extension validation

          // thanks to JohnPaul Bader: dynamicregularexpresions/

          if(String(MultiFileaccept)length>){

                                   MultiFileaccept = MultiFileacceptreplace(/\W+/g|)replace(/^\W|\W$/g);

           MultiFilerxAccept = new RegExp(\\(+(MultiFileaccept?MultiFileaccept:)+)$gi);

          };

  

          //===

  

          // Create wrapper to hold our file list

          MultiFilewrapID = MultiFileinstanceKey+_wrap; // Wrapper ID?

          MultiFileEwrap(<div class=MultiFilewrap id=+MultiFilewrapID+></div>);

          MultiFilewrapper = $(#+MultiFilewrapID+);

  

          //===

  

          // MultiFile MUST have a name default: file[] file[] file[]

          MultiFileename = MultiFileename || file+ group_count +[];

  

          //===

  

                               if(!MultiFilelist){

                                   // Create a wrapper for the list

                                   // * OPERA BUG: NO_MODIFICATION_ALLOWED_ERR (list is a readonly property)

                                   // this change allows us to keep the files in the order they were selected

                                   MultiFilewrapperappend( <div class=MultiFilelist id=+MultiFilewrapID+_list></div> );

                                   MultiFilelist = $(#+MultiFilewrapID+_list);

                               };

          MultiFilelist = $(MultiFilelist);

  

          //===

  

          // Bind a new element

          MultiFileaddSlave = function( slave slave_count ){

                                   //if(nsole) consolelog(MultiFileaddSlaveslave_count);

  

           // Keep track of how many elements have been displayed

           MultiFilen++;

           // Add reference to master element

           slaveMultiFile = MultiFile;

  

                                   // BUG FIX:

                                   // Clear identifying properties from clones

                                   if(slave_count>) slaveid = slavename = ;

  

           // Define elements ID and name (upload components need this!)

           //slaveid = slaveid || MultiFilegenerateID(slave_count);

                                   if(slave_count>) slaveid = MultiFilegenerateID(slave_count);

                                   //FIX for: multifileplugin/issues/detail?id=

  

           // Apr: New customizable naming convention (see url below)

           // dev/browse_frm/thread/cebf#

           slavename = String(MultiFilenamePattern

            /*master name*/replace(/\$name/gi$(MultiFileclone)attr(name))

            /*master id  */replace(/\$id/gi  $(MultiFileclone)attr(id))

            /*group count*/replace(/\$g/gi   group_count)//(group_count>?group_count:))

            /*slave count*/replace(/\$i/gi   slave_count)//(slave_count>?slave_count:))

           );

  

           // If weve reached maximum number disable input slave

           if( (MultiFilemax > ) && ((MultiFilen) > (MultiFilemax)) )//{ // MultiFilen Starts at so subtract to find true count

            slavedisabled = true;

           //};

  

           // Remember most recent slave

           MultiFilecurrent = MultiFileslaves[slave_count] = slave;

  

                                   // Well use jQuery from now on

                                   slave = $(slave);

  

           // Clear value

           slaveval()attr(value)[]value = ;

  

                                   // Stop plugin initializing on slaves

                                   slaveaddClass(MultiFileapplied);

  

           // Triggered when a file is selected

           slavechange(function(){

             //if(nsole) consolelog(MultiFileslavechangeslave_count);

  

             // Lose focus to stop IE firing onchange again

             $(this)blur();

  

             //# Trigger Event! onFileSelect

             if(!MultiFiletrigger(onFileSelect this MultiFile)) return false;

             //# End Event!

  

             //# Retrive value of selected file from element

             var ERROR = v = String(thisvalue || /*attr(value)*/);

  

             // check extension

             if(MultiFileaccept && v && !vmatch(MultiFilerxAccept))//{

               ERROR = MultiFileSTRINGdeniedreplace($ext String(vmatch(/\\w{}$/gi)));

              //}

             //};

  

             // Disallow duplicates

                                           for(var f in MultiFileslaves)//{

              if(MultiFileslaves[f] && MultiFileslaves[f]!=this)//{

                                             //consolelog(MultiFileslaves[f]MultiFileslaves[f]value);

               if(MultiFileslaves[f]value==v)//{

                ERROR = MultiFileSTRINGduplicatereplace($file vmatch(/[^\/\\]+$/gi));

               //};

              //};

             //};

  

             // Create a new file input element

             var newEle = $(MultiFileclone)clone();// Copy parent attributes Thanks to Jonas Wagner

             //# Lets remember which input weve generated so

             // we can disable the empty ones before submission

             // See:

             newEleaddClass(MultiFile);

  

             // Handle error

             if(ERROR!=){

               // Handle error

               MultiFileerror(ERROR);

  

               // : BUG FIX Thanks to Adrian Wr骲el <adrian [dot] wrobel [at] >

               // Ditch the trouble maker and add a fresh new element

               MultiFilen;

               MultiFileaddSlave(newEle[] slave_count);

               slaveparent()prepend(newEle);

               slaveremove();

               return false;

             };

  

             // Hide this element (NB: display:none is evil!)

             $(this)css({ position:absolute top: px });

  

             // Add new element to the form

             slaveafter(newEle);

  

             // Update list

             MultiFileaddToList( this slave_count );

  

             // Bind functionality

             MultiFileaddSlave( newEle[] slave_count+ );

  

             //# Trigger Event! afterFileSelect

             if(!MultiFiletrigger(afterFileSelect this MultiFile)) return false;

             //# End Event!

  

           }); // slavechange()

  

                                   // Save control to element

                                   $(slave)data(MultiFile MultiFile);

  

          };// MultiFileaddSlave

          // Bind a new element

  

  

  

          // Add a new file to the list

          MultiFileaddToList = function( slave slave_count ){

           //if(nsole) consolelog(MultiFileaddToListslave_count);

  

           //# Trigger Event! onFileAppend

           if(!MultiFiletrigger(onFileAppend slave MultiFile)) return false;

           //# End Event!

  

           // Create label elements

           var

            r = $(<div class=MultiFilelabel></div>)

            v = String(slavevalue || /*attr(value)*/)

            a = $(<span class=MultiFiletitle title=+MultiFileSTRINGselectedreplace($file v)+>+MultiFileSTRINGfilereplace($file vmatch(/[^\/\\]+$/gi)[])+</span>)

            b = $(<a class=MultiFileremove #+MultiFilewrapID+>+MultiFileSTRINGremove+</a>);

  

           // Insert label

           MultiFilelistappend(

            rappend(b a)

           );

  

           b

                                   click(function(){

  

             //# Trigger Event! onFileRemove

             if(!MultiFiletrigger(onFileRemove slave MultiFile)) return false;

             //# End Event!

  

             MultiFilen;

             MultiFilecurrentdisabled = false;

  

             // Remove element remove label point to current

                                           MultiFileslaves[slave_count] = null;

                                           $(slave)remove();

                                           $(this)parent()remove();

  

             // Show most current element again (move into view) and clear selection

             $(MultiFilecurrent)css({ position: top: });

                                           $(MultiFilecurrent)reset()val()attr(value )[]value = ;

  

             //# Trigger Event! afterFileRemove

             if(!MultiFiletrigger(afterFileRemove slave MultiFile)) return false;

             //# End Event!

  

             return false;

           });

  

           //# Trigger Event! afterFileAppend

           if(!MultiFiletrigger(afterFileAppend slave MultiFile)) return false;

           //# End Event!

  

          }; // MultiFileaddToList

          // Add element to selected files list

  

  

  

          // Bind functionality to the first element

          if(!MultiFileMultiFile) MultiFileaddSlave(MultiFilee );

  

          // Increment control count

          //MultiFileI++; // using windowMultiFile

          MultiFilen++;

  

                               // Save control to element

                               MultiFileEdata(MultiFile MultiFile);

  

  

               //#####################################################################

               // MAIN PLUGIN FUNCTIONALITY END

               //#####################################################################

           }); // each element

       };

  

       /**/

  

       /*

           ### Core functionality and API ###

       */

       $extend($fnMultiFile {

     /**

      * This method removes all selected files

      *

      * Returns a jQuery collection of all affected elements

      *

      * @name reset

      * @type jQuery

      * @cat Plugins/MultiFile

      * @author Diego A ()

      *

      * @example $fnMultiFilereset();

      */

     reset: function(){

               var settings = $(this)data(MultiFile);

               //if(settings) settingswrapperfind(aMultiFileremove)click();

               if(settings) settingslistfind(aMultiFileremove)click();

      return $(this);

     }

  

  

     /**

      * This utility makes it easy to disable all empty file elements in the document before submitting a form

      * It marks the affected elements so they can be easily reenabled after the form submission or validation

      *

      * Returns a jQuery collection of all affected elements

      *

      * @name disableEmpty

      * @type jQuery

      * @cat Plugins/MultiFile

      * @author Diego A ()

      *

      * @example $fnMultiFiledisableEmpty();

      * @param String class (optional) A string specifying a class to be applied to all affected elements Default: mfD

      */

     disableEmpty: function(klass){ klass = String(klass || mfD);

      var o = [];

      $(input:file)each(function(){ if($(this)val()==) o[olength] = this; });

      return $(o)each(function(){ thisdisabled = true })addClass(klass);

     }

  

  

    /**

     * This method reenables empty file elements that were disabled (and marked) with the $fnMultiFiledisableEmpty method

     *

     * Returns a jQuery collection of all affected elements

     *

     * @name reEnableEmpty

     * @type jQuery

     * @cat Plugins/MultiFile

     * @author Diego A ()

     *

     * @example $fnMultiFilereEnableEmpty();

     * @param String klass (optional) A string specifying the class that was used to mark affected elements Default: mfD

     */

     reEnableEmpty: function(klass){ klass = String(klass || mfD);

      return $(input:file+klass)removeClass(klass)each(function(){ thisdisabled = false });

     }

  

  

    /**

     * This method will intercept other jQuery plugins and disable empty file input elements prior to form submission

     *

  

     * @name intercept

     * @cat Plugins/MultiFile

     * @author Diego A ()

     *

     * @example $fnMultiFileintercept();

     * @param Array methods (optional) Array of method names to be intercepted

     */

     intercepted: {}

     intercept: function(methods context args){

      var method value; args = args || [];

      if(nstructortoString()indexOf(Array)<) args = [ args ];

      if(typeof(methods)==function){

       $fnMultiFiledisableEmpty();

       value = methodsapply(context || window args);

                   //SEEmultifileplugin/issues/detail?id=

                   setTimeout(function(){ $fnMultiFilereEnableEmpty() });

       return value;

      };

      if(nstructortoString()indexOf(Array)<) methods = [methods];

      for(var i=;i<methodslength;i++){

       method = methods[i]+; // make sure that we have a STRING

       if(method) (function(method){ // make sure that method is ISOLATED for the interception

        $fnMultiFileintercepted[method] = $fn[method] || function(){};

        $fn[method] = function(){

         $fnMultiFiledisableEmpty();

         value = $fnMultiFileintercepted[method]apply(this arguments);

                           //SEEmultifileplugin/issues/detail?id=

         setTimeout(function(){ $fnMultiFilereEnableEmpty() });

         return value;

        }; // interception

       })(method); // MAKE SURE THAT method IS ISOLATED for the interception

      };// for each method

     }

    });

  

       /**/

  

       /*

           ### Default Settings ###

           eg: You can override default control like this:

           $fnMultiFileoptionsaccept = gif|jpg;

       */

       $fnMultiFileoptions = { //$extend($fnMultiFile { options: {

           accept: // accepted file extensions

           max:     // maximum number of selectable files

  

           // name to use for newly created elements

           namePattern: $name // same name by default (which creates an array)

  

           // STRING: collection lets you show messages in different languages

           STRING: {

               remove:x

               denied:You cannot select a $ext file\nTry again

               file:$file

               selected:File selected: $file

               duplicate:This file has already been selected:\n$file

           }

  

           // name of methods that should be automcatically intercepted so the plugin can disable

           // extra file elements that are empty before execution and automatically reenable them afterwards

     autoIntercept: [ submit ajaxSubmit ajaxForm validate /* array of methods to intercept */ ]

  

           // error handling function

           error: function(s){

               /*

               ERROR! blockUI is not currently working in IE

               if($blockUI){

                   $blockUI({

                       message: sreplace(/\n/gi<br/>)

                       css: {

                           border:none padding:px size:pt

                           backgroundColor:# color:#fff

                           opacity:webkitborderradius: pxmozborderradius: px

                       }

                   });

                   windowsetTimeout($unblockUI );

               }

               else//{// save a byte!

               */

                alert(s);

               //}// save a byte!

           }

    }; //} });

  

       /**/

  

       /*

           ### Additional Methods ###

           Required functionality outside the plugins scope

       */

  

       // Native input reset method because this alone doesnt always work: $(element)val()attr(value )[]value = ;

       $fnreset = function(){ return thiseach(function(){ try{ thisreset(); }catch(e){} }); };

  

       /**/

  

       /*

           ### Default implementation ###

           The plugin will attach itself to file inputs

           with the class multi when the page loads

       */

       $(function(){

     //$(input:filemulti)MultiFile();

     $(input[type=file]multi)MultiFile();

    });

  

  

  

   /*# AVOID COLLISIONS #*/

   })(jQuery);

   /*# AVOID COLLISIONS #*/

  

  哲學管理(學)人生 文學藝術生活 自動(計算機學)物理(學)工作 生物(學)化學逆境 歷史(學)測繪(學)時間 經濟(學)數學金錢(理財) 心理(學)醫學情緒 詩詞美容情感 美學建築(學)家園 解構(分析)整合學習 情商(EQ)運籌(學)成功Geovin Du(塗聚文)


From:http://tw.wingwit.com/Article/program/net/201311/13435.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.