jquery写入json文件 C#用jquery多个文件上传
C#用jquery多个文件上传
<%@ Page Language= C# AutoEventWireup= true CodeBehind= Default aspx cs Inherits= UploadFile _Default %>
<!DOCTYPE PUBLIC //W C//DTD XHTML Transitional//EN transitional dtd >
< xmlns= >
<head runat= server >
<title>Upload Multiple Files in ASP NET Using jQuery</title>
<script src= Scripts/jquery js type= text/javascript ></script>
<script src= Scripts/jquery MultiFile js 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>
</>
服务器端代码
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;
using System IO;
namespace UploadFile
{
/// <summary>
/// 多个文件上传
/// 涂聚文 QQ:
/// </summary>
public partial class _Default : System Web UI Page
{
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 = Request Files;
for (int i = ; i < hfc Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf ContentLength > )
{
string name=System IO Path GetFileName(hpf FileName);
if (name Contains( ))
{
System Random srd = new Random();
int srdName = srd Next( );
name = name Substring(name LastIndexOf( ) name Length name LastIndexOf( ));
name = DateTime Now ToString( yyyyMMddhhmmss ) + srdName ToString() + name;
}
// FileUpload PostedFile SaveAs(Server MapPath( upimge/ ) + name);
if (hfc Count == )
{
fi = name;
}
if (hfc Count!= )
{
//file += name;
fi += name+ ; ;
}
//创造年 月 日的文件夹
//string year = DateTime Now Year ToString();
//string month = DateTime Now Month ToString();
//string day = DateTime Now Day ToString();
//if (Directory Exists( upload + \ + year) == false)
//{
// Directory CreateDirectory( upload + \ + year);
//}
//if (Directory Exists( upload + \ + year + \ + month) == false)
//{
// Directory CreateDirectory( upload + \ + year + \ + month);
//}
//if (Directory Exists( upload + \ + year + \ + month + \ + day) == false)
//{
// Directory CreateDirectory( upload + \ + year + \ + month + \ + day);
//}
//保存地址this TextBox Text = / + year + / + month + / + day + / +name;
hpf SaveAs(Server MapPath( upload ) + \ + name);
//hpf SaveAs(Server MapPath( upload ) + \ + System IO Path GetFileName(hpf FileName));
// Response Write( <b>File: </b> + hpf FileName + <b>Size:</b> +
//hpf ContentLength + <b>Type:</b> + hpf ContentType + Uploaded Successfully <br/> );
}
this TextBox Text = fi;
}
}
catch (Exception ex)
{
}
}
/// <summary>
///
/// </summary>
/// <param name= jsContent ></param>
//protected void WriteJs(string jsContent)
//{
// ClientScript RegisterStartupScript(this GetType() writejs <script type= text/javascript > + jsContent + </script> );
//}
}
}
jquery MultiFile js代码
/*
### jQuery Multiple File Upload Plugin v ###
* Home: file upload/
* Code: multifile plugin/
*
* Dual licensed under the MIT and GPL licenses:
* license php
*
###
*/
;if(window jQuery) (function($){
// plugin initialization
$ fn MultiFile = function(options){
if(this length== ) return this; // quick fail
// Handle API methods
if(typeof arguments[ ]== string ){
// Perform API methods on individual elements
if(this length> ){
var args = arguments;
return this each(function(){
$ fn MultiFile apply($(this) args);
});
};
// Invoke API method handler
$ fn MultiFile[arguments[ ]] apply(this $ makeArray(arguments) slice( ) || []);
// Quick exit
return this;
};
// Initialize options for this call
var options = $ extend(
{}
$ fn MultiFile options
options || {}
);
// Empty Element Fix!!!
// this code will automatically intercept native form submissions
// and disable empty file elements
$( form )
not( MultiFile intercepted )
addClass( MultiFile intercepted )
submit($ fn MultiFile disableEmpty);
//###
// utility method to integrate this plugin with others
if($ fn MultiFile options autoIntercept){
$ fn MultiFile intercept( $ fn MultiFile options autoIntercept );
$ fn MultiFile options autoIntercept = null;
};
// loop through each matched element
this
not( MultiFile applied )
addClass( MultiFile applied )
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
window MultiFile = (window MultiFile || ) + ;
var group_count = window MultiFile;
// 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({}
$ fn MultiFile options
options || {}
(tadata? tadata(): (ta?MultiFile E data():null)) || {}
{}
);
// limit number of files that can be selected?
if(!(o max> ) ){
o max = MultiFile E attr( maxlength );
if(!(o max> ) ){
o max = (String(MultiFile e className match(/b(max|limit) ([ ]+)b/gi) || [ ]) match(/[ ]+/gi) || [ ])[ ];
if(!(o max> )) o max = ;
else o max = String(o max) match(/[ ]+/gi)[ ];
}
};
o max = new Number(o max);
// limit extensions?
o accept = o accept || MultiFile E attr( accept ) || ;
if(!o accept){
o accept = (MultiFile e className match(/b(accept [w|]+)b/gi)) || ;
o accept = new String(o accept) replace(/^(accept|ext) /i );
};
//===
// APPLY CONFIGURATION
$ extend(MultiFile o || {});
MultiFile STRING = $ extend({} $ fn MultiFile options STRING MultiFile STRING);
//===
//#########################################
// PRIVATE PROPERTIES/METHODS
$ extend(MultiFile {
n: // How many elements are currently selected?
slaves: [] files: []
instanceKey: MultiFile e id || MultiFile +String(group_count) // Instance Key?
generateID: function(z){ return MultiFile instanceKey + (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 John Paul Bader: dynamic regular expresions/
if(String(MultiFile accept) length> ){
MultiFile accept = MultiFile accept replace(/W+/g | ) replace(/^W|W$/g );
MultiFile rxAccept = new RegExp( \ ( +(MultiFile accept?MultiFile accept: )+ )$ gi );
};
//===
// Create wrapper to hold our file list
MultiFile wrapID = MultiFile instanceKey+ _wrap ; // Wrapper ID?
MultiFile E wrap( <div class= MultiFile wrap id= +MultiFile wrapID+ ></div> );
MultiFile wrapper = $( # +MultiFile wrapID+ );
//===
// MultiFile MUST have a name default: file [] file [] file []
MultiFile e name = MultiFile e name || file + group_count + [] ;
//===
if(!MultiFile list){
// Create a wrapper for the list
// * OPERA BUG: NO_MODIFICATION_ALLOWED_ERR ( list is a read only property)
// this change allows us to keep the files in the order they were selected
MultiFile wrapper append( <div class= MultiFile list id= +MultiFile wrapID+ _list ></div> );
MultiFile list = $( # +MultiFile wrapID+ _list );
};
MultiFile list = $(MultiFile list);
//===
// Bind a new element
MultiFile addSlave = function( slave slave_count ){
//if(nsole) console log( MultiFile addSlave slave_count);
// Keep track of how many elements have been displayed
MultiFile n++;
// Add reference to master element
slave MultiFile = MultiFile;
// BUG FIX:
// Clear identifying properties from clones
if(slave_count> ) slave id = slave name = ;
// Define element s ID and name (upload ponents need this!)
//slave id = slave id || MultiFile generateID(slave_count);
if(slave_count> ) slave id = MultiFile generateID(slave_count);
//FIX for: multifile plugin/issues/detail?id=
// Apr : New customizable naming convention (see url below)
// dev/browse_frm/thread/ c e b f #
slave name = String(MultiFile namePattern
replace(/$name/gi $(MultiFile clone) attr( name ))
replace(/$id/gi $(MultiFile clone) attr( id ))
replace(/$g/gi group_count)//(group_count> ?group_count: ))
replace(/$i/gi slave_count)//(slave_count> ?slave_count: ))
);
// If we ve reached maximum number disable input slave
if( (MultiFile max > ) && ((MultiFile n ) > (MultiFile max)) )//{ // MultiFile n Starts at so subtract to find true count
slave disabled = true;
//};
// Remember most recent slave
MultiFile current = MultiFile slaves[slave_count] = slave;
// We ll use jQuery from now on
slave = $(slave);
// Clear value
slave val( ) attr( value )[ ] value = ;
// Stop plugin initializing on slaves
slave addClass( MultiFile applied );
// Triggered when a file is selected
slave change(function(){
//if(nsole) console log( MultiFile slave change slave_count);
// Lose focus to stop IE firing onchange again
$(this) blur();
//# Trigger Event! onFileSelect
if(!MultiFile trigger( onFileSelect this MultiFile)) return false;
//# End Event!
//# Retrive value of selected file from element
var ERROR = v = String(this value || );

// check extension
if(MultiFile accept && v && !v match(MultiFile rxAccept))//{
ERROR = MultiFile STRING denied replace( $ext String(v match(/ w{ }$/gi)));
//}
//};
// Disallow duplicates
for(var f in MultiFile slaves)//{
if(MultiFile slaves[f] && MultiFile slaves[f]!=this)//{
//console log(MultiFile slaves[f] MultiFile slaves[f] value);
if(MultiFile slaves[f] value==v)//{
ERROR = MultiFile STRING duplicate replace( $file v match(/[^/\]+$/gi));
//};
//};
//};
// Create a new file input element
var newEle = $(MultiFile clone) clone();// Copy parent attributes Thanks to Jonas Wagner
//# Let s remember which input we ve generated so
// we can disable the empty ones before submission
// See:
newEle addClass( MultiFile );
// Handle error
if(ERROR!= ){
// Handle error
MultiFile error(ERROR);
// : BUG FIX Thanks to Adrian Wr骲el <adrian [dot] wrobel [at] >
// Ditch the trouble maker and add a fresh new element
MultiFile n ;
MultiFile addSlave(newEle[ ] slave_count);
slave parent() prepend(newEle);
slave remove();
return false;
};
// Hide this element (NB: display:none is evil!)
$(this) css({ position: absolute top: px });
// Add new element to the form
slave after(newEle);
// Update list
MultiFile addToList( this slave_count );
// Bind functionality
MultiFile addSlave( newEle[ ] slave_count+ );
//# Trigger Event! afterFileSelect
if(!MultiFile trigger( afterFileSelect this MultiFile)) return false;
//# End Event!
}); // slave change()
// Save control to element
$(slave) data( MultiFile MultiFile);
};// MultiFile addSlave
// Bind a new element
// Add a new file to the list
MultiFile addToList = function( slave slave_count ){
//if(nsole) console log( MultiFile addToList slave_count);
//# Trigger Event! onFileAppend
if(!MultiFile trigger( onFileAppend slave MultiFile)) return false;
//# End Event!
// Create label elements
var
r = $( <div class= MultiFile label ></div> )
v = String(slave value || )
a = $( <span class= MultiFile title title= +MultiFile STRING selected replace( $file v)+ > +MultiFile STRING file replace( $file v match(/[^/\]+$/gi)[ ])+ </span> )
b = $( <a class= MultiFile remove # +MultiFile wrapID+ > +MultiFile STRING remove+ </a> );
// Insert label
MultiFile list append(
r append(b a)
);
b
click(function(){
//# Trigger Event! onFileRemove
if(!MultiFile trigger( onFileRemove slave MultiFile)) return false;
//# End Event!
MultiFile n ;
MultiFile current disabled = false;
// Remove element remove label point to current
MultiFile slaves[slave_count] = null;
$(slave) remove();
$(this) parent() remove();
// Show most current element again (move into view) and clear selection
$(MultiFile current) css({ position: top: });
$(MultiFile current) reset() val( ) attr( value )[ ] value = ;
//# Trigger Event! afterFileRemove
if(!MultiFile trigger( afterFileRemove slave MultiFile)) return false;
//# End Event!
return false;
});
//# Trigger Event! afterFileAppend
if(!MultiFile trigger( afterFileAppend slave MultiFile)) return false;
//# End Event!
}; // MultiFile addToList
// Add element to selected files list
// Bind functionality to the first element
if(!MultiFile MultiFile) MultiFile addSlave(MultiFile e );
// Increment control count
//MultiFile I++; // using window MultiFile
MultiFile n++;
// Save control to element
MultiFile E data( MultiFile MultiFile);
//#####################################################################
// MAIN PLUGIN FUNCTIONALITY END
//#####################################################################
}); // each element
};
$ extend($ fn MultiFile {
/**
* 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 $ fn MultiFile reset();
*/
reset: function(){
var settings = $(this) data( MultiFile );
//if(settings) settings wrapper find( a MultiFile remove ) click();
if(settings) settings list find( a MultiFile remove ) 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 re enabled 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 $ fn MultiFile disableEmpty();
* @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[o length] = this; });
return $(o) each(function(){ this disabled = true }) addClass(klass);
}
/**
* This method re enables empty file elements that were disabled (and marked) with the $ fn MultiFile disableEmpty method
*
* Returns a jQuery collection of all affected elements
*
* @name reEnableEmpty
* @type jQuery
* @cat Plugins/MultiFile
* @author Diego A ()
*
* @example $ fn MultiFile reEnableEmpty();
* @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(){ this disabled = 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 $ fn MultiFile intercept();
* @param Array methods (optional) Array of method names to be intercepted
*/
intercepted: {}
intercept: function(methods context args){
var method value; args = args || [];
if(nstructor toString() indexOf( Array )< ) args = [ args ];
if(typeof(methods)== function ){
$ fn MultiFile disableEmpty();
value = methods apply(context || window args);
//SEE multifile plugin/issues/detail?id=
setTimeout(function(){ $ fn MultiFile reEnableEmpty() } );
return value;
};
if(nstructor toString() indexOf( Array )< ) methods = [methods];
for(var i= ;i<methods length;i++){
method = methods[i]+ ; // make sure that we have a STRING
if(method) (function(method){ // make sure that method is ISOLATED for the interception
$ fn MultiFile intercepted[method] = $ fn[method] || function(){};
$ fn[method] = function(){
$ fn MultiFile disableEmpty();
value = $ fn MultiFile intercepted[method] apply(this arguments);
//SEE multifile plugin/issues/detail?id=
setTimeout(function(){ $ fn MultiFile reEnableEmpty() } );
return value;
}; // interception
})(method); // MAKE SURE THAT method IS ISOLATED for the interception
};// for each method
}
});
$ fn MultiFile options = { //$ extend($ fn MultiFile { 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 re enable them afterwards
autoIntercept: [ submit ajaxSubmit ajaxForm validate ]
// error handling function
error: function(s){
alert(s);
//}// save a byte!
}
}; //} });
// Native input reset method because this alone doesn t always work: $(element) val( ) attr( value )[ ] value = ;
$ fn reset = function(){ return this each(function(){ try{ this reset(); }catch(e){} }); };
$(function(){
//$( input:file multi ) MultiFile();
$( input[type=file] multi ) MultiFile();
});
})(jQuery);
lishixinzhi/Article/program/net/201311/13435