客户端代码
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UploadFile._Default" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml" >
 6 <head runat="server">
 7     <title>Upload Multiple Files in ASP.NET Using jQuery</title>
 8         <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
 9         <script src="Scripts/jquery.MultiFile.js" type="text/javascript"></script>
10 </head>
11 <body>
12     <form id="form1" runat="server">
13     <div>
14         <asp:TextBox ID="TextBox1" runat="server" Height="79px" TextMode="MultiLine"></asp:TextBox>
15         <asp:FileUpload ID="FileUpload1" runat="server" CssClass="multi" /><asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
16     </div>
17     
18     </form>
19 </body>
20 </html>

 

服务器端代码
  1 using System;
  2 using System.Data;
  3 using System.Configuration;
  4 using System.Collections;
  5 using System.Web;
  6 using System.Web.Security;
  7 using System.Web.UI;
  8 using System.Web.UI.WebControls;
  9 using System.Web.UI.WebControls.WebParts;
 10 using System.Web.UI.HtmlControls;
 11 using System.IO;
 12 
 13 namespace UploadFile
 14 {
 15     /// <summary>
 16     /// 多个文件上传
 17     /// 涂聚文 QQ:463588883  www.dusystem.com
 18     /// </summary>
 19     public partial class _Default : System.Web.UI.Page
 20     {
 21 
 22         string fi;
 23         protected void Page_Load(object sender, EventArgs e)
 24         {
 25 
 26         }
 27         /// <summary>
 28         /// 
 29         /// </summary>
 30         /// <param name="sender"></param>
 31         /// <param name="e"></param>
 32         protected void btnUpload_Click(object sender, EventArgs e)
 33         {
 34             try
 35             {
 36                 //多个文件
 37                 
 38                 // Get the HttpFileCollection
 39                 HttpFileCollection hfc = Request.Files;
 40                 for (int i = 0; i < hfc.Count; i++)
 41                 {
 42                     
 43                     HttpPostedFile hpf = hfc[i];
 44                     if (hpf.ContentLength > 0)
 45                     {
 46                         string name=System.IO.Path.GetFileName(hpf.FileName);
 47                         if (name.Contains("."))
 48                         {
 49                             System.Random srd = new Random();
 50                             int srdName = srd.Next(1000);
 51                             name = name.Substring(name.LastIndexOf("."), name.Length - name.LastIndexOf("."));
 52                             name = DateTime.Now.ToString("yyyyMMddhhmmss"+ srdName.ToString() + name;
 53                         }
 54                        // FileUpload2.PostedFile.SaveAs(Server.MapPath("upimge/") + name);
 55                         if (hfc.Count == 1)
 56                         {
 57                             fi = name;
 58                         }
 59                         if (hfc.Count!= 1)
 60                         {
 61                             //file += name;
 62                             fi += name+";";
 63                         }
 64                         //创造年,月,日的文件夹
 65                         //string year = DateTime.Now.Year.ToString();
 66                         //string month = DateTime.Now.Month.ToString();
 67                         //string day = DateTime.Now.Day.ToString();
 68                         //if (Directory.Exists("upload" + "\\" + year) == false)
 69                         //{
 70                         //    Directory.CreateDirectory("upload" + "\\" + year);
 71                         //}
 72                         //if (Directory.Exists("upload" + "\\" + year + "\\" + month) == false)
 73                         //{
 74                         //    Directory.CreateDirectory("upload" + "\\" + year + "\\" + month);
 75                         //}
 76                         //if (Directory.Exists("upload" + "\\" + year + "\\" + month + "\\" + day) == false)
 77                         //{
 78                         //    Directory.CreateDirectory("upload" + "\\" + year + "\\" + month + "\\" + day);
 79                         //}
 80                         //保存地址this.TextBox1.Text ="/" + year + "/" + month + "/" + day +"/"+name;
 81                         hpf.SaveAs(Server.MapPath("upload"+ "\\" + name);
 82                         //hpf.SaveAs(Server.MapPath("upload") + "\\" + System.IO.Path.GetFileName(hpf.FileName));
 83                        // Response.Write("<b>File: </b>" + hpf.FileName + "  <b>Size:</b> " +
 84                             //hpf.ContentLength + "  <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
 85                     }
 86                     this.TextBox1.Text = fi;
 87                 }
 88                 
 89             }
 90             catch (Exception ex)
 91             {
 92 
 93             }
 94         }
 95         /// <summary>
 96         /// 
 97         /// </summary>
 98         /// <param name="jsContent"></param>
 99         //protected void WriteJs(string jsContent)
100         //{
101 
102         //    ClientScript.RegisterStartupScript(this.GetType(), "writejs", "<script type='text/javascript'>" + jsContent + "</script>");
103         //}
104 
105 
106     }
107 }

 

jquery.MultiFile.js代码
  1 /*
  2  ### jQuery Multiple File Upload Plugin v1.45 - 2009-04-22 ###
  3  * Home: http://www.fyneworks.com/jquery/multiple-file-upload/
  4  * Code: http://code.google.com/p/jquery-multifile-plugin/
  5  *
  6  * Dual licensed under the MIT and GPL licenses:
  7  *   http://www.opensource.org/licenses/mit-license.php
  8  *   http://www.gnu.org/licenses/gpl.html
  9  ###
 10 */
 11 
 12 /*# AVOID COLLISIONS #*/
 13 ;if(window.jQuery) (function($){
 14 /*# AVOID COLLISIONS #*/
 15  
 16     // plugin initialization
 17     $.fn.MultiFile = function(options){
 18         if(this.length==0return this// quick fail
 19         
 20         // Handle API methods
 21         if(typeof arguments[0]=='string'){
 22             // Perform API methods on individual elements
 23             if(this.length>1){
 24                 var args = arguments;
 25                 return this.each(function(){
 26                     $.fn.MultiFile.apply($(this), args);
 27     });
 28             };
 29             // Invoke API method handler
 30             $.fn.MultiFile[arguments[0]].apply(this, $.makeArray(arguments).slice(1|| []);
 31             // Quick exit...
 32             return this;
 33         };
 34         
 35         // Initialize options for this call
 36         var options = $.extend(
 37             {}/* new object */,
 38             $.fn.MultiFile.options/* default options */,
 39             options || {} /* just-in-time options */
 40         );
 41         
 42         // Empty Element Fix!!!
 43         // this code will automatically intercept native form submissions
 44         // and disable empty file elements
 45         $('form')
 46         .not('MultiFile-intercepted')
 47         .addClass('MultiFile-intercepted')
 48         .submit($.fn.MultiFile.disableEmpty);
 49         
 50         //### http://plugins.jquery.com/node/1363
 51         // utility method to integrate this plugin with others...
 52         if($.fn.MultiFile.options.autoIntercept){
 53             $.fn.MultiFile.intercept( $.fn.MultiFile.options.autoIntercept /* array of methods to intercept */ );
 54             $.fn.MultiFile.options.autoIntercept = null/* only run this once */
 55         };
 56         
 57         // loop through each matched element
 58         this
 59          .not('.MultiFile-applied')
 60             .addClass('MultiFile-applied')
 61         .each(function(){
 62             //#####################################################################
 63             // MAIN PLUGIN FUNCTIONALITY - START
 64             //#####################################################################
 65             
 66        // BUG 1251 FIX: http://plugins.jquery.com/project/comments/add/1251
 67        // variable group_count would repeat itself on multiple calls to the plugin.
 68        // this would cause a conflict with multiple elements
 69        // changes scope of variable to global so id will be unique over n calls
 70        window.MultiFile = (window.MultiFile || 0+ 1;
 71        var group_count = window.MultiFile;
 72        
 73        // Copy parent attributes - Thanks to Jonas Wagner
 74        // we will use this one to create new input elements
 75        var MultiFile = {e:this, E:$(this), clone:$(this).clone()};
 76        
 77        //===
 78        
 79        //# USE CONFIGURATION
 80        if(typeof options=='number') options = {max:options};
 81        var o = $.extend({},
 82         $.fn.MultiFile.options,
 83         options || {},
 84                        ($.metadata? MultiFile.E.metadata(): ($.meta?MultiFile.E.data():null)) || {}, /* metadata options */
 85                                 {} /* internals */
 86        );
 87        // limit number of files that can be selected?
 88        if(!(o.max>0/*IsNull(MultiFile.max)*/){
 89         o.max = MultiFile.E.attr('maxlength');
 90         if(!(o.max>0/*IsNull(MultiFile.max)*/){
 91          o.max = (String(MultiFile.e.className.match(/\b(max|limit)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];
 92          if(!(o.max>0)) o.max = -1;
 93          else           o.max = String(o.max).match(/[0-9]+/gi)[0];
 94         }
 95        };
 96        o.max = new Number(o.max);
 97        // limit extensions?
 98        o.accept = o.accept || MultiFile.E.attr('accept'|| '';
 99        if(!o.accept){
100         o.accept = (MultiFile.e.className.match(/\b(accept\-[\w\|]+)\b/gi)) || '';
101         o.accept = new String(o.accept).replace(/^(accept|ext)\-/i,'');
102        };
103        
104        //===
105        
106        // APPLY CONFIGURATION
107                             $.extend(MultiFile, o || {});
108        MultiFile.STRING = $.extend({},$.fn.MultiFile.options.STRING,MultiFile.STRING);
109        
110        //===
111        
112        //#########################################
113        // PRIVATE PROPERTIES/METHODS
114        $.extend(MultiFile, {
115         n: 0// How many elements are currently selected?
116         slaves: [], files: [],
117         instanceKey: MultiFile.e.id || 'MultiFile'+String(group_count), // Instance Key?
118         generateID: function(z){ return MultiFile.instanceKey + (z>0 ?'_F'+String(z):''); },
119         trigger: function(event, element){
120          var handler = MultiFile[event], value = $(element).attr('value');
121          if(handler){
122           var returnValue = handler(element, value, MultiFile);
123           if( returnValue!=null ) return returnValue;
124          }
125          return true;
126         }
127        });
128        
129        //===
130        
131        // Setup dynamic regular expression for extension validation
132        // - thanks to John-Paul Bader: http://smyck.de/2006/08/11/javascript-dynamic-regular-expresions/
133        if(String(MultiFile.accept).length>1){
134                                 MultiFile.accept = MultiFile.accept.replace(/\W+/g,'|').replace(/^\W|\W$/g,'');
135         MultiFile.rxAccept = new RegExp('\\.('+(MultiFile.accept?MultiFile.accept:'')+')$','gi');
136        };
137        
138        //===
139        
140        // Create wrapper to hold our file list
141        MultiFile.wrapID = MultiFile.instanceKey+'_wrap'// Wrapper ID?
142        MultiFile.E.wrap('<div class="MultiFile-wrap" >

 

相关文章: