Complete uploadify batch file upload plug-in, uploadify uploads files
1. First, prepare the uploadify js file.
2. upload page UpFilePage. aspx
Key code:
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> upload a file </title>
<Link href = "/jquery. uploadify/uploadify.css" rel = "stylesheet"/>
<Script type = "text/javascript" src = "/jquery. uploadify/jquery-1.8.3.min.js"> </script>
<Script src = "/jquery. uploadify/swfobject. js" charset = "UTF-8"> </script>
<Script src = "/jquery. uploadify/jquery. uploadify. v2.1.0.js"> </script>
<Style type = "text/css">
# FileSave {padding-left: 5px; padding-right: 5px ;}
# FileSave. uploadifyQueueItem {width: 530px ;}
# FileQueue {padding-left: 5px; padding-right: 5px ;}
# FileQueue. uploadifyQueueItem {width: 530px ;}
# UploadifyUploader {position: absolute; opacity: 0 ;}
. Uploadify-button {height: 30px; line-height: 30px; width: pixel PX; text-align: center; border: 0px; margin-bottom: 5px; background: # ff6600; color: # fff ;}
. Cancel a {background: url (/jquery. uploadify/cancel.png) no-repeat center; display: inline-block; width: 16px; height: 16px ;}
</Style>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div> <% = GetFile () %>
</Div>
</Div>
</Div>
</Form>
<Script type = "text/javascript">
Var fileCount = 0;
$ (Document). ready (function (){
FileCount = $ ("# fileSave> div. uploadifyQueueItem"). length;
$ ("Input [name = 'radphone']: eq (0)"). attr ("checked", "checked ");
$ ("# Uploadify"). uploadify ({
'Upload': '/jquery. uploadify/uploadify.swf', // relative path of the uploadify.swf File
'Script': '/jquery. uploadify/uploadHandler. ashx', // The program that processes files.
// 'Cancelim': '/Scripts/jquery. uploadify/cancel.png', // cancel the image
// 'Folder': 'upfiles', // directory for storing uploaded files
'Queue id': 'filequeue ', // ID of the file queue
// 'Filedesc ':'*. flv ;*. mp4 ;*. wmv ;*. avi ;*. 3gp ;*. mpg ;*. ppt ;*. pptx ', // upload format restrictions
// 'Text ':'*. flv ;*. mp4 ;*. wmv ;*. avi ;*. 3gp ;*. mpg ;*. ppt ;*. pptx ', // upload format restrictions
"QueueSizeLimit": "5", // when multiple files are allowed to be generated, set the number of selected files
'Auto': true, // set to true. When a file is selected, it is uploaded directly.
'Multi ': true, // multiple files can be uploaded when set to true.
"FileDataName": "imgFile", // set a name based on the name in the server processing program.
"SizeLimit": "5242880", // size limit of the uploaded file, in bytes
"SimUploadLimit": "1", // The number of simultaneous uploads allowed. Default Value: 1
"OnSelect": function (e, queueId, fileObj ){
FileCount = $ ("# fileSave> div. uploadifyQueueItem"). length;
Var less = 5-fileCount;
If (less <= 0 ){
Layer. msg ("up to five attachments can be uploaded ");
$ ("# A_upload"). attr ("href", "javascript :");
Return false;
} Else {
$ ("# A_upload"). attr ("href", "javascript: $ ('# uploadify'). uploadifyUpload ()");
Return true;
}
},
"OnComplete": function (){
$. Ajax ({
Type: "post ",
Url: "/UploadAction/UploadHandler. ashx ",
Data: {operate: "GetFile "},
Async: false,
Success: function (objdata ){
$ ("# FileSave" pai.html (objdata );
FileCount = $ ("# fileSave> div. uploadifyQueueItem"). length;
Var less = 5-fileCount;
If (less <= 0 ){
$ ("# A_upload"). attr ("href", "javascript :");
$ ("# FileQueue" pai.html ("");
Return false;
} Else {
$ ("# A_upload"). attr ("href", "javascript: $ ('# uploadify'). uploadifyUpload ()");
Return true;
}
}
});
},
"OnCancel": function (){
FileCount = $ ("# fileSave> div. uploadifyQueueItem"). length;
Var less = 5-fileCount;
If (less <= 0 ){
$ ("# A_upload"). attr ("href", "javascript :");
Return false;
} Else {
$ ("# A_upload"). attr ("href", "javascript: $ ('# uploadify'). uploadifyUpload ()");
Return true;
}
},
});
});
Function deleteFile (path ){
$. Ajax ({
Type: "post ",
Url: "/UploadAction/UploadHandler. ashx ",
Data: {operate: "deleteFile", file: path },
Success: function (objdata ){
$ ("# FileSave" pai.html (objdata );
FileCount = $ ("# fileSave> div. uploadifyQueueItem"). length;
Var less = 5-fileCount;
If (less <= 0 ){
$ ("# A_upload"). attr ("href", "javascript :");
} Else
$ ("# A_upload"). attr ("href", "javascript: $ ('# uploadify'). uploadifyUpload ()");
}
});
}
</Script>
</Body>
</Html>
The GetFile () method in the background:
/// <Summary>
/// Obtain cookie Attachment Information
/// </Summary>
/// <Returns> </returns>
Protected string GetFile ()
{
# Region obtain cookie Attachment Information
StringBuilder strHtml = new StringBuilder ();
HttpCookie fileCookie = Request. Cookies ["FileCookie"];
If (fileCookie! = Null)
{
String [] fileArray = new string [1];
If (fileCookie. Value. Contains ("| "))
FileArray = fileCookie. Value. Split ('| ');
Else
FileArray [0] = fileCookie. Value;
Foreach (string objFile in fileArray)
{
If (! String. IsNullOrEmpty (objFile) & objFile. Contains (","))
{
String [] file = objFile. Split (',');
StrHtml. Append (@ "<div class = 'uploadifyqueueitem'> ");
StrHtml. Append (@ "<div class = 'cancel'> ");
StrHtml. Append ("<a href = 'javascript: deleteFile (\" "+ file [1] +" \ ") '> </a> ");
// StrHtml. Append (@ " ");
StrHtml. Append (@ "</div> ");
StrHtml. append (@ "<span class = 'filename'>" + HttpUtility. urlDecode (file [0]) + "</span> <span class = 'centage'>-100% </span> <div class = 'uploadifyss ss'> ");
StrHtml. Append (@ "<div class = 'uploadifyprogressbar 'style = 'width: 100%;'> ");
StrHtml. Append (@ "</div> ");
StrHtml. Append (@ "</div> ");
StrHtml. Append (@ "</div> ");
}
}
}
Return strHtml. ToString ();
# Endregion
}
3. General handlers in the UploadAction Folder:
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
String operate = context. Request ["operate"];
If (operate = "deleteFile ")
{
# Region delete file attachment information
// Obtain the file path
String filePath = context. Server. MapPath (context. Request ["file"]);
// Determine whether a file exists
If (File. Exists (filePath ))
File. Delete (filePath); // Delete an object
// Obtain the cookie information of the attachment.
HttpCookie fileCookie = context. Request. Cookies ["FileCookie"];
String [] fileArray = new string [1];
If (fileCookie! = Null)
{
FilePath = filePath. Remove (0, filePath. IndexOf ("upfiles"). Replace ("\\","/");
If (fileCookie. Value. Contains ("| "))
FileArray = fileCookie. Value. Split ('| ');
Else
FileArray [0] = fileCookie. Value;
String strFile = "";
For (int I = 0; I <fileArray. Length; I ++)
{
If (! FileArray [I]. Contains (filePath ))
StrFile + = fileArray [I] + "| ";
}
If (strFile. Contains ("| "))
StrFile = strFile. Remove (strFile. Length-1 );
FileCookie. Value = strFile;
FileCookie. Expires = DateTime. Now. AddDays (1 );
FileCookie. HttpOnly = true;
Context. Response. AppendCookie (fileCookie );
StringBuilder strHtml = new StringBuilder ();
If (fileCookie. Value. Contains ("| "))
FileArray = fileCookie. Value. Split ('| ');
Else
FileArray [0] = fileCookie. Value;
Foreach (string objFile in fileArray)
{
If (! String. IsNullOrEmpty (objFile) & objFile. Contains (","))
{
String [] file = objFile. Split (',');
StrHtml. Append (@ "<div class = 'uploadifyqueueitem'> ");
StrHtml. Append (@ "<div class = 'cancel'> ");
StrHtml. Append ("<a href = 'javascript: deleteFile (\" "+ file [1] +" \ ") '> </a> ");
// StrHtml. Append (@ " ");
StrHtml. Append (@ "</div> ");
StrHtml. append (@ "<span class = 'filename'>" + HttpUtility. urlDecode (file [0]) + "</span> <span class = 'centage'>-100% </span> <div class = 'uploadifyss ss'> ");
StrHtml. Append (@ "<div class = 'uploadifyprogressbar 'style = 'width: 100%;'> ");
StrHtml. Append (@ "</div> ");
StrHtml. Append (@ "</div> ");
StrHtml. Append (@ "</div> ");
}
}
Context. Response. Write (strHtml. ToString ());
}
# Endregion
}
Else if (operate = "GetFile ")
{
# Region obtain and display uploaded attachments
StringBuilder strHtml = new StringBuilder ();
HttpCookie fileCookie = context. Request. Cookies ["FileCookie"];
If (fileCookie! = Null)
{
String [] fileArray = new string [1];
If (fileCookie. Value. Contains ("| "))
FileArray = fileCookie. Value. Split ('| ');
Else
FileArray [0] = fileCookie. Value;
Foreach (string objFile in fileArray)
{
If (! String. IsNullOrEmpty (objFile) & objFile. Contains (","))
{
String [] file = objFile. Split (',');
StrHtml. Append (@ "<div class = 'uploadifyqueueitem'> ");
StrHtml. Append (@ "<div class = 'cancel'> ");
StrHtml. Append ("<a href = 'javascript: deleteFile (\" "+ file [1] +" \ ") '> ");
// StrHtml. Append (@ " </a> ");
StrHtml. Append (@ "</div> ");
StrHtml. append (@ "<span class = 'filename'>" + HttpUtility. urlDecode (file [0]) + "</span> <span class = 'centage'>-100% </span> <div class = 'uploadifyss ss'> ");
StrHtml. Append (@ "<div class = 'uploadifyprogressbar 'style = 'width: 100%;'> ");
StrHtml. Append (@ "</div> ");
StrHtml. Append (@ "</div> ");
StrHtml. Append (@ "</div> ");
}
}
}
Context. Response. Write (strHtml. ToString ());
# Endregion
}
}
4. Upload the file uploadHandler. ashx general processing code. The file upload path can be set as needed:
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
HttpCookie fileCookie = context. Request. Cookies ["FileCookie"];
If (fileCookie! = Null)
{
String [] fileArray = new string [1];
If (fileCookie. Value. Contains ("| "))
FileArray = fileCookie. Value. Split ('| ');
If (fileArray. Length> = 5)
Return;
}
Else
{
FileCookie = new HttpCookie ("FileCookie ");
FileCookie. Value = "";
Context. Response. Cookies. Add (fileCookie );
}
String aspxUrl = context. Request. Path. Substring (0, context. Request. Path. LastIndexOf ("/") + 1 );
// Path of the file storage directory
String savePath = "/upfiles /";
// File Save directory URL
String saveUrl = "/upfiles /";
// If (context. Request. Cookies ["Member"]! = Null)
//{
// SavePath + = context. Request. Cookies ["Member"] ["MemberId"] + "/";
// SaveUrl + = context. Request. Cookies ["Member"] ["MemberId"] + "/";
//}
String Member = Guid. NewGuid (). ToString (). Trim (). Replace ("-","");
SavePath + = Member + "/";
SaveUrl + = Member + "/";
// Define the file extension that can be uploaded
/* Hashtable extTable = new Hashtable ();
ExtTable. Add ("image", "gif, jpg, jpeg, png, bmp ");
ExtTable. Add ("flash", "swf, flv ");
ExtTable. Add ("media", "swf, flv, mp3, wav, wma, wmv, mid, avi, mpg, asf, rm, rmvb, mp4 ");
ExtTable. add ("file", "doc, docx, xls, xlsx, ppt, htm, html, txt, zip, rar, gz, bz2, swf, flv, mp3, wav, wma, wmv, mid, avi, mpg, asf, rm, rmvb, mp4, wps ");*/
// Maximum File Size
Int maxSize = 5242880;
HttpPostedFile imgFile = context. Request. Files ["imgFile"];
/* If (imgFile = null)
{
ShowError ("select a file. ");
}*/
String dirPath = context. Server. MapPath (savePath );
If (! Directory. Exists (dirPath ))
{
Directory. CreateDirectory (dirPath );
// ShowError ("the upload directory does not exist. ");
}
String dirName = context. Request. QueryString ["dir"];
If (String. IsNullOrEmpty (dirName ))
{
DirName = "file ";
}
/* If (! ExtTable. ContainsKey (dirName ))
{
ShowError ("the directory name is incorrect. ");
}*/
String fileName = imgFile. FileName;
String fileExt = Path. GetExtension (fileName). ToLower ();
/* If (String. isNullOrEmpty (fileExt) | Array. indexOf (String) extTable [dirName]). split (','), fileExt. substring (1 ). toLower () =-1)
{
ShowError ("the upload file extension is not allowed. \ N only supports the "+ (String) extTable [dirName]) +" format. ");
}
If (dirName. Contains ("image "))
{
If (imgFile. InputStream = null | imgFile. InputStream. Length> maxSize)
{
ShowError ("the size of the uploaded file exceeds the limit of 5 MB. ");
}
}*/
// Create a folder
DirPath + = dirName + "/";
SaveUrl + = dirName + "/";
If (! Directory. Exists (dirPath ))
{
Directory. CreateDirectory (dirPath );
}
String ymd = DateTime. Now. ToString ("yyyyMMdd", DateTimeFormatInfo. InvariantInfo );
DirPath + = ymd + "/";
SaveUrl + = ymd + "/";
If (! Directory. Exists (dirPath ))
{
Directory. CreateDirectory (dirPath );
}
String newFileName = DateTime. Now. ToString ("yyyyMMddHHmmss_ffff", DateTimeFormatInfo. InvariantInfo) + fileExt;
String filePath = dirPath + newFileName;
ImgFile. SaveAs (filePath );
String fileUrl = saveUrl + newFileName;
/* Hashtable hash = new Hashtable ();
Hash ["error"] = 0;
Hash ["url"] = fileUrl;
Context. Response. AddHeader ("Content-Type", "text/html; charset = UTF-8 ");
Context. Response. Write (JsonMapper. ToJson (hash ));
Context. Response. End ();*/
If (fileCookie! = Null)
{
String strFile = fileCookie. Value;
If (! String. IsNullOrEmpty (strFile ))
StrFile = strFile + "|" + HttpUtility. UrlEncode (fileName) + "," + fileUrl;
Else
StrFile = HttpUtility. UrlEncode (fileName) + "," + fileUrl;
FileCookie. Value = strFile;
FileCookie. Expires = DateTime. Now. AddDays (1 );
FileCookie. HttpOnly = true;
Context. Response. AppendCookie (fileCookie );
}
Context. Response. Write ("1 ");
Context. Response. End ();
}
5. After all the codes are completed, you can get the results: