ASP. NET uploadify for multi-attachment upload function

Source: Internet
Author: User
The example of this article for you to share the ASP. Uploadify Multi-Attachment upload method, for your reference, the specific content as follows





1. Description



Uploadify is an excellent jquery plugin, the main function is to upload files in bulk. Most students are difficult to upload multiple attachments, will be ASP. Uploadfiy How to implement bulk upload attachments to everyone to explain, there is nothing wrong place also please a lot of communication, the following code paste out everyone together to communicate.



2. Composition



Let's start by explaining the techniques used to implement the Code for reference only:



Development tools: VS2010



Target framework:. NET Framework3.5



uploadify:uploadify-v3.1



Jquery:jquery-1.8.1.js



Finally I will upload the entire demo, if the students have a development environment on their computer can directly open the project solution to run.



3. Code



Default.aspx (Test page)

<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "Default.aspx.cs" Inherits = "FileUpload._Default"%>
  
<! DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
 <title> Attachment upload </ title>
 <script src = "Scripts / jquery-1.8.1.js" type = "text / javascript"> </ script>
 <script src = "Scripts / uploadify-v3.1 / jquery.uploadify-3.1.js" type = "text / javascript"> </ script>
 <link href = "Scripts / uploadify-v3.1 / uploadify.css" rel = "stylesheet" type = "text / css" />
 <script type = "text / javascript">
 $ (function () {
  $ ("# file_upload"). uploadify ({
  "auto": false,
  "swf": "Scripts / uploadify-v3.1 / uploadify.swf",
  "uploader": "App_Handler / Uploadify.ashx? action = upload",
  "removeCompleted": false,
  "onUploadSuccess": function (file, data, response) {
   alert ('file' + file.name + 'has been uploaded successfully and returns' + response + 'server status' + data);
  }
  });
 });
 </ script>
</ head>
<body>
 <form id = "form1" runat = "server">
 <div>
 <input type = "file" id = "file_upload" name = "file_upload" />
 </ div>
 <div>
 <a href="javascript:$('#file_upload').uploadify('upload');"> upload the first </a>
 <a href="javascript:$('#file_upload').uploadify('upload','*');"> Upload queue </a>
 <a href="javascript:$('#file_upload').uploadify('cancel');"> Cancel the first </a>
 <a href="javascript:$('#file_upload').uploadify('cancel','*');"> Cancel the queue </a>
 </ div>
 </ form>
</ body>
</ html>




Uploadify.ashx (general handler)

<% @ WebHandler Language = "C #" Class = "UploadifyUpload"%>
  
using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.SessionState;
using System.IO;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Text;
  
public class UploadifyUpload: IHttpHandler, IRequiresSessionState
{
  
 public void ProcessRequest (HttpContext context)
 {
 context.Response.ContentType = "text / plain";
 context.Response.Charset = "utf-8";
  
 string action = context.Request ["action"];
 switch (action)
 {
  case "upload":
  //Upload Attachment
  upload (context);
  break;
 }
 context.Response.End ();
 }
  
 /// <summary>
 /// Upload Attachment
 /// </ summary>
 /// <param name = "context"> </ param>
 private void upload (HttpContext context)
 {
 HttpPostedFile postedFile = context.Request.Files ["Filedata"];
 if (postedFile! = null)
 {
  string fileName, fileExtension;
  int fileSize;
  fileName = postedFile.FileName;
  fileSize = postedFile.ContentLength;
  if (fileName! = "")
  {
  
  fileExtension = postedFile.FileName.Substring (postedFile.FileName.LastIndexOf ('.'));
  string path = context.Server.MapPath ("/") + "\\ App_Attachments \\"; // Set the path of the file
  string fileUrl = path + DateTime.Now.ToString ("yyyyMMddHHmmss") + fileExtension; // Save file path
  if (! Directory.Exists (path)) {
   Directory.CreateDirectory (path);
  }
  postedFile.SaveAs (fileUrl); // Save the source file first
  
  
  context.Response.Write ("Upload succeeded!");
  
  }
  else
  {
  context.Response.Write ("Upload failed!");
  }
 }
 else
 {
  context.Response.Write ("Upload failed!");
 }
 }
  
 public bool IsReusable
 {
 get
 {
  return false;
 }
 }
  
}




4.Supplement

Post some explanations of uploadfiy parameters for everyone. The method of use is to configure $ ("# file_upload"). Uploadify ({}); in the Default.aspx test page. Configure the method. Regardless of the parameter or event configuration, use a comma in English. End, the last one does not need a comma to end. Similar to



The detailed parameters are as follows:

// required parameters
id: $ this.attr ('id'), // ID of the DOM object
  
swf: 'Scripts / jquery-uploadify / uploadify.swf', // Path to the uploadify.swf file
  
uploader: 'App_Handler / Uploadify.ashx', // relative path to the background handler
  
auto: false, // Set to true when the file is selected and uploaded directly. If it is false, you need to click the upload button to upload. Here doDoload () method
  
buttonClass: '', // button style
  
buttonCursor: 'hand', // How the mouse pointer will hover over the button
  
buttonImage: null, // path to the image of the browse button
  
buttonText: 'Select file', // Browse button text
  
checkExisting: false, // The file upload repetitive check program checks whether the file to be uploaded already exists on the server side, returns 1 if it exists, and returns 0 if it does not exist
  
debug: false, // if set to true, enable debug mode of SWFUpload
  
fileObjName: 'Filedata', // The name of the file upload object. If it is named 'the_files', PHP programs can use $ _FILES ['the_files'] to process the uploaded file objects.
  
fileSizeLimit: '5MB', // The size limit of the uploaded file, if it is an integer, it means the size in KB, if it is a string, you can use (B, KB, MB, or GB) as a unit, such as' 2MB '; if set to 0, unlimited
  
fileTypeDesc: 'Supported formats:', // This attribute value must be set after the fileTypeExts attribute is set to be effective. It is used to set the prompt text in the select file dialog. For example, if you set fileTypeDesc to "Please select a rar doc pdf file"
  
fileTypeExts: '*. *', // Set the file type that can be selected, such as: '* .doc; *. pdf; *. rar'
  
height: 24, // set the height of the browse button, default value
  
itemTemplate: false, // HTML template for setting the upload queue, you can use the following tags: instanceID – ID of the Uploadify instance fileID – ID of this file in the queue, or ID for this task fileName – name of the file fileSize – current The size of the uploaded file is inserted into the template tag using the format such as: $ {fileName}
  
method: 'post', // Post or Get
  
multi: true, // multiple files can be uploaded when set to true
  
formData: {'action': 'upload'}, // Additional data submitted to the server while uploading each file in AnJSON format can be dynamically set using the 'settings' method in the 'onUploadStart' event
  
preventCaching: true, // if true, a string of random string parameters will be automatically added each time a file is uploaded to prevent the URL cache from affecting the upload result
  
progressData: 'percentage', // Set the upload progress display method, percentage display upload percentage, speed display upload speed
  
listID: false, // Set the ID of the DOM element of the attachment list container
  
queueID: false, // Set the ID of the DOM element of the upload queue container, if false, automatically generate a queue container
  
queueSizeLimit: 999, // The maximum number of tasks displayed in the queue. If the number of selected files exceeds this limit, the onSelectError event will be triggered. Note that this is not the maximum number of file uploads. If you want to limit the maximum number of uploaded files, you should set uploadLimit
  
removeCompleted: false, // whether to automatically delete completed tasks from the queue, if set to true will remove from the queue
  
removeTimeout: 3, // If the task is automatically removed from the queue after completion, you can specify Time between completion and removal
  
requeueErrors: false, // If set to true, an error will be returned after a single task upload fails, and rejoin the task queue to upload
  
successTimeout: 30, // The server should return a success flag after the file has been uploaded successfully. This item sets the timeout for the returned result
  
uploadLimit: 0, // The maximum number of uploaded files, if this limit is reached or exceeded, the onUploadError event will be triggered
  
width: 75, // set the width of the file browse button


Set events:

onDialogClose: function (swfuploadifyQueue) {// Triggered when the file selection dialog is closed
If (swfuploadifyQueue.filesErrored> 0) {
Alert ('When adding to queue'
+ SwfuploadifyQueue.filesErrored
+ 'File error n'
+ 'Error message:'
+ SwfuploadifyQueue.errorMsg
+ 'NNumber of selected files:'
+ SwfuploadifyQueue.filesSelected
+ 'NNumber of files successfully added to the queue:'
+ SwfuploadifyQueue.filesQueued
+ 'N Total number of files in queue:'
+ SwfuploadifyQueue.queueLength);
}
}
  
onDialogOpen: function () {// Triggered when the select file dialog opens
Alert ('Open!');
}
  
  
  
onSelect: function (file) {// Triggered after each file is added to the queue
Alert ('id:' + file.id
+ '-Index:' + file.index
+ '-File name:' + file.name
+ '-File size:' + file.size
+ '-Type:' + file.type
+ '-Creation date:' + file.creationdate
+ '-Modification date:' + file.modificationdate
+ '-File status:' + file.filestatus);
}
  
  
  
onSelectError: function (file, errorCode, errorMsg) {// Triggered when a file selection error occurs
Alert ('id:' + file.id
+ '-Index:' + file.index
+ '-File name:' + file.name
+ '-File size:' + file.size
+ '-Type:' + file.type
+ '-Creation date:' + file.creationdate
+ '-Modification date:' + file.modificationdate
+ '-File status:' + file.filestatus
+ '-Error code:' + errorCode
+ '-Error message:' + errorMsg);
}
  
  
  
onQueueComplete: function (stats) {// Triggered when all files in the queue have finished uploading
Alert ('Number of files successfully uploaded:' + stats.successful_uploads
+ '-Number of files with upload errors:' + stats.upload_errors
+ '-Number of files canceled:' + stats.upload_cancelled
+ '-Number of files with errors' + stats.queue_errors);
}
  
  
  
onUploadComplete: function (file, swfuploadifyQueue) {// Triggered once when each file in the queue is uploaded
Alert ('id:' + file.id
+ '-Index:' + file.index
+ '-File name:' + file.name
+ '-File size:' + file.size
+ '-Type:' + file.type
+ '-Creation date:' + file.creationdate
+ '-Modification date:' + file.modificationdate
+ '-File status:' + file.filestatus
+ '-Number of files in error:' + swfuploadifyQueue.filesErrored
+ '-Error message:' + swfuploadifyQueue.errorMsg
+ '-The number to add to the queue:' + swfuploadifyQueue.filesSelected
+ '-Added to the opposite number:' + swfuploadifyQueue.filesQueued
+ '-Queue length:' + swfuploadifyQueue.queueLength);
}
  
  
  
onUploadError: function (file, errorCode, errorMsg, errorString, swfuploadifyQueue) {// Upload file error is triggered (triggered once per error file)
Alert ('id:' + file.id
+ '-Index:' + file.index
+ '-File name:' + file.name
+ '-File size:' + file.size
+ '-Type:' + file.type
+ '-Creation date:' + file.creationdate
+ '-Modification date:' + file.modificationdate
+ '-File status:' + file.filestatus
+ '-Error code:' + errorCode
+ '-Error description:' + errorMsg
+ '-Brief error description:' + errorString
+ '-Number of files in error:' + swfuploadifyQueue.filesErrored
+ '-Error message:' + swfuploadifyQueue.errorMsg
+ '-The number to add to the queue:' + swfuploadifyQueue.filesSelected
+ '-Added to the opposite number:' + swfuploadifyQueue.filesQueued
+ '-Queue length:' + swfuploadifyQueue.queueLength);
}
  
  
  
onUploadProgress: function (file, fileBytesLoaded, fileTotalBytes,
queueBytesLoaded, swfuploadifyQueueUploadSize) {// Triggered when the upload progress changes
alert ('id:' + file.id
+ '-Index:' + file.index
+ '-File name:' + file.name
+ '-File size:' + file.size
+ '-Type:' + file.type
+ '-Creation date:' + file.creationdate
+ '-Modification date:' + file.modificationdate
+ '-File status:' + file.filestatus
+ '-The current file has been uploaded:' + fileBytesLoaded
+ '-Current file size:' + fileTotalBytes
+ '-Queue uploaded:' + queueBytesLoaded
+ '-Queue size:' + swfuploadifyQueueUploadSize);
}
  
  
  
onUploadStart: function (file) {// Triggered when uploading starts (triggered once per file)
Alert ('id:' + file.id
+ '-Index:' + file.index
+ '-File name:' + file.name
+ '-File size:' + file.size
+ '-Type:' + file.type
+ '-Creation date:' + file.creationdate
+ '-Modification date:' + file.modificationdate
+ '-File status:' + file.filestatus);
}
  
onUploadSuccess: function (file, data, response) {// Triggered when upload is complete (triggered once for each file)
Alert ('id:' + file.id
+ '-Index:' + file.index
+ '-File name:' + file.name
+ '-File size:' + file.size
+ '-Type:' + file.type
+ '-Creation date:' + file.creationdate
+ '-Modification date:' + file.modificationdate
+ '-File status:' + file.filestatus
+ '-Server-side message:' + data
+ '-Whether the upload was successful:' + response);
  
}
5. Finally, Demo: FileUpload

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone supports topic.alibabacloud.com.

 

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.