asp.net uploadify implement multi-Attachment upload function _ Practical skills

Source: Internet
Author: User
Tags file upload httpcontext rar save file

The example of this article for everyone to share the asp.net uploadify multiple attachment upload method for your reference, the specific contents are as follows

1, the description

Uploadify is a good jquery plug-in, the main function is to bulk upload files. Most of the students to upload a lot of attachments are tricky, now will asp.net combined with uploadfiy how to achieve the bulk upload attachment to everyone to explain, what is wrong place also please a lot of exchanges and communication, the following code posted out to communicate with everyone.

2. Composition

First, explain the technology used by the code implementation, 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 the computer can directly open the project solution run.

3, Code

Default.aspx (Test page)

<%@ Page language= "C #" autoeventwireup= "true" codebehind= "Default.aspx.cs" inherits= "Fileupload._default"%> & lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
 ">  

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 UPL Oad (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\\";//settings file path 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 context first. Response.Write ("Upload success!")
 
  "); } else {context. Response.Write ("Upload failed!")
  "); } else {context. Response.Write ("Upload failed!")
 ");
 } public bool IsReusable {get {false;
 }
 }
 
}
  

4, supplementary

For you to post some uploadfiy parameters, using the method is in the Default.aspx test page $ ("#file_upload"). Uploadify ({}); The configuration in the method, regardless of whether the parameter or event configuration is to end with a comma in English state, The last one does not need a comma to end. Similar to the following figure

The detailed parameters are as follows:

Required parameter ID: $this. attr (' id '),//DOM object ID swf: ' scripts/jquery-uploadify/uploadify.swf ',//uploadify.swf file path Uplo Ader: ' app_handler/uploadify.ashx ',//Background handler relative path Auto:false,//set to True when the file is selected directly uploaded, for false need to click upload button to upload, here to perform doupload () method Buttonclass: ',//button style Buttoncursor: ' Hand ',///mouse pointer hover over button to look buttonimage:null,//browse button's picture path ButtonText: ' Select File ',//browse button text Checkexisting:false,//File Upload repeatability Checker, check whether the file will be uploaded on the server side already exists, the existence returns 1, does not exist returns 0 Debug:false,//If set to True to indicate
 
Enable SWFUpload debug mode fileobjname: ' Filedata ',//File upload object name, if named ' The_files ', PHP program can use $_files[' the_files ' to process uploaded file object Filesizelimit: ' 5MB ',//upload file size limit, if the integer is the size of KB, if it is a string, you can use (B, KB, MB, or GB) as a unit, such as ' 2MB '; If set to 0, it means unrestricted filetyped ESC: ' Supported format: '///This property value must be set filetypeexts property to be valid to set the prompt text in the Select File dialog box, such as setting Filetypedesc to "Please select RAR doc PDF File" filetypeexts: ' *.* ',//Set the type of file that can be selected, format such as: ' *.doc;*.pdf;*.rar ' height:24,//Set browse button height, default value itemtemplate:false,///To set up HTML template for upload queue, can be used to Under Label: instanceid–uploadify Instance ID fileid – The ID of this file in the queue, or the name of the ID filename– file for this task filesize– the size of the current upload file to insert the template label using the format such as: ${filename} method: ' Post ',//Submit way post or get Multi:true,//set to True when multiple files can be uploaded formData: {' action ': ' Upload '},///Anjson format upload each file at the same time the additional data submitted to the server can be in ' Onuploadstart ' event Using the ' settings ' method to dynamically set Preventcaching:true,//If True, automatically add a string of random string parameters each time the file is uploaded to prevent URL caching from affecting upload results progressdata: ' Percentage ', Set upload progress display mode, percentage display upload percentage, speed display upload speed Listid:false,//Set Attachment list container DOM element ID queueid:false,//Set upload queue container DOM element ID, if False automatically generates a queue container queuesizelimit:999,//The maximum number of tasks displayed by the queue, and if the number of files selected exceeds this limit, the Onselecterror event will be started.
 
Note 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 the completed task is automatically removed from the queue, if set to Ture will be removed from the queue Removetimeout:3,//If the task is completed and automatically removed from the queue, you can specify that the interval between completion and removal requeueerrors:false,//If set to True, an error will be returned if a single task fails to upload. and rejoin the task queue upload successtimeout:30,//File upload success after the server should return the success of the flag, this setting returns the result of the timeout uploadlimit:0,//maximum number of uploaded files, if reached or exceeded this limit will trigger Onuploade
 Rror event width:75,//Set the width of the file browse button

  Set events:  

Ondialogclose:function (Swfuploadifyqueue) {////When the File selection dialog box closes, triggers if (swfuploadifyqueue.fileserrored > 0) {alert (' Add to Queue with ' +swfuploadifyqueue.fileserrored + ' file error n ' + ' error message: ' +swfuploadifyqueue.errormsg + ' n selected number of files: ' +swfuploadi Fyqueue.filesselected + ' n The number of files successfully added to the queue: ' +swfuploadifyqueue.filesqueued + ' n the total number of files in the queue: ' +swfuploadifyqueue.queuelengt
  h);
 
 
 
} ondialogopen:function () {//Trigger alert (' open! ') when the Select File dialog box is open; 
  Onselect:function (file) {///When each file is added to the queue triggers alert (' ID: ' + file.id + '-index: ' + file.index + '-filename: ' + file.name + '-File size: ' + file.size + '-type: ' + File.type + '-Date Created: ' + file.creationdate + '-Modification date: ' + File.modifica
Tiondate + '-File status: ' + File.filestatus '; Onselecterror:function (file,errorcode,errormsg) {////When error occurred in file selection triggers alert (' ID: ' + file.id + '-index: ' + file.i
  Ndex + '-filename: ' + file.name + '-File size: ' + file.size + '-type: ' + File.type + '-Date Created: ' + file.creationdate + '-Modification date: ' + FIle.modificationdate + '-File status: ' + file.filestatus + '-Error code: ' + errorcode + '-error message: ' + errormsg '; Onqueuecomplete:function (stats) {////When all files in the queue are complete upload alert (' Number of files successfully uploaded: ' + stats.successful_uploads + '-on
Number of outgoing files: ' + stats.upload_errors + '-Number of files canceled: ' + stats.upload_cancelled + '-Number of files in error ' + stats.queue_errors ';  Onuploadcomplete:function (File,swfuploadifyqueue) {///queue Every file uploaded completes triggers once alert (' ID: ' + file.id + '-index: ' + File.index + '-filename: ' + file.name + '-File size: ' + file.size + '-type: ' + File.type + '-Date Created: ' + File.creati Ondate + '-Modified: ' + file.modificationdate + '-File status: ' + File.filestatus + '-Number of files in error: ' + swfuploadifyqueue.fil eserrored + '-error message: ' + swfuploadifyqueue.errormsg + '-number to add to queue: ' + swfuploadifyqueue.filesselected + '-Add to
Number of legislation: ' + swfuploadifyqueue.filesqueued + '-Queue Length: ' + swfuploadifyqueue.queuelength '; } onuploaderror:function (FILE,ERRORCODE,ERRORMSG,ERRORSTRING,SWFuploadifyqueue) {//Upload file error is triggered (every error file triggers once) alert (' ID: ' + file.id + '-index: ' + file.index + '-filename: ' + file.name + '-File size: ' + file.size + '-type: ' + File.type + '-Date Created: ' + file.creationdate + '-Modification date: ' + File.modificat Iondate + '-File status: ' + file.filestatus + '-Error code: ' + errorcode + '-Error description: ' + errormsg + '-Brief error description: ' + Error String + '-Number of files in error: ' + swfuploadifyqueue.fileserrored + '-error message: ' + swfuploadifyqueue.errormsg + '-Number of queues to add: ' + swfuploadifyqueue.filesselected + '-added to the opposing number: ' + swfuploadifyqueue.filesqueued + '-Queue Length: ' + swfuploadifyqueu
E.queuelength); } onuploadprogress:function (File,filebytesloaded,filetotalbytes, queuebytesloaded,swfuploadifyqueueuploadsize) {/  /Upload Progress Changes trigger alert (' ID: ' + file.id + '-index: ' + file.index + '-filename: ' + file.name + '-File size: ' + file.size + '-type: ' + File.type + '-Date Created: ' + file.creationdate + '-Modified: ' + file.modificationdate + '-File status: ' + file. FilestatuS + '-current file uploaded: ' + filebytesloaded + '-Current file size: ' + filetotalbytes + '-Queue uploaded: ' + queuebytesloaded + '-Queue size
: ' + swfuploadifyqueueuploadsize); Onuploadstart:function (file) {//upload at start (each trigger once) alert (' ID: ' + file.id + '-index: ' + file.index + '-file  Name: ' + file.name + '-File size: ' + file.size + '-type: ' + File.type + '-Date Created: ' + file.creationdate + '-Modified Date: '
+ file.modificationdate + '-File status: ' + File.filestatus '; Onuploadsuccess:function (file,data,response) {//upload complete trigger (once per file trigger) alert (' ID: ' + file.id + '-index: ' + file.ind
  ex + '-filename: ' + file.name + '-File size: ' + file.size + '-type: ' + File.type + '-Date Created: ' + file.creationdate + '-Modification date: ' + file.modificationdate + '-File status: ' + File.filestatus + '-server-side message: ' + data + '-upload success: ' + RESPO
 
NSE);
 }

5, the last to serve Demo:fileupload

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.