Home Backend Development C#.Net Tutorial asp.net uploadify implements multiple attachment upload function

asp.net uploadify implements multiple attachment upload function

Dec 20, 2016 pm 02:11 PM

本文实例为大家分享了asp.net uploadify多附件上传的方法,供大家参考,具体内容如下

1、说明

  uploadify是一款优秀jQuery插件,主要功能是批量上传文件。大多数同学对多附件上传感到棘手,现将asp.net结合uploadfiy如何实现批量上传附件给大家讲解一下,有什么不对的地方还请大家多多交流沟通,下面把代码贴出来大家一起交流。

2、组成

首先说明一下代码实现所用到的技术,仅供参考:

    开发工具:vs2010

    目标框架:.NET Framework3.5

    Uploadify:uploadify-v3.1

    Jquery:jquery-1.8.1.js

最后我会将整个Demo上传,如果同学们的电脑上有开发环境可直接打开项目解决方案运行。

3、代码

Default.aspx(测试页面)

<%@ 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>附件上传</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(&#39;文件 &#39; + file.name + &#39; 已经上传成功,并返回 &#39; + response + &#39; 服务器状态 &#39; + data);
  }
  });
 });
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <input type="file" id="file_upload" name="file_upload" />
 </div>
 <div>
 <a href="javascript:$(&#39;#file_upload&#39;).uploadify(&#39;upload&#39;);">上传第一个</a>
 <a href="javascript:$(&#39;#file_upload&#39;).uploadify(&#39;upload&#39;,&#39;*&#39;);">上传队列</a>
 <a href="javascript:$(&#39;#file_upload&#39;).uploadify(&#39;cancel&#39;);">取消第一个</a>
 <a href="javascript:$(&#39;#file_upload&#39;).uploadify(&#39;cancel&#39;, &#39;*&#39;);">取消队列</a>
 </div>
 </form>
</body>
</html>
Copy after login



Uploadify.ashx(一般处理程序)

<%@ 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(context);
  break;
 }
 context.Response.End();
 }
  
 /// <summary>
 /// 上传附件
 /// </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(&#39;.&#39;));
  string path =context.Server.MapPath("/")+ "\\App_Attachments\\";//设置文件的路径
  string fileUrl = path + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension;//保存文件路径
  if (!Directory.Exists(path)) {
   Directory.CreateDirectory(path);
  }
  postedFile.SaveAs(fileUrl);//先保存源文件
  
  
  context.Response.Write("上传成功!");
  
  }
  else
  {
  context.Response.Write("上传失败!");
  }
 }
 else
 {
  context.Response.Write("上传失败!");
 }
 }
  
 public bool IsReusable
 {
 get
 {
  return false;
 }
 }
  
}
Copy after login


  

4、补充

  给大家贴出一些uploadfiy参数的讲解,使用方法就是在Default.aspx测试页面里面$("#file_upload").uploadify({});方法中配置,不论参数或事件配置要以英文状态下的逗号结束,最后一个不需要逗号结束。类似于下图


详细参数如下:

// 所需的参数
id: $this.attr(&#39;id&#39;), // DOM对象的ID
  
swf: &#39;Scripts/jquery-uploadify/uploadify.swf&#39;, // uploadify.swf 文件的路径
  
uploader: &#39;App_Handler/Uploadify.ashx&#39;, // 后台处理程序的相对路径
  
auto: false, // 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传,这里执行doUpload()方法
  
buttonClass: &#39;&#39;, // 按钮样式
  
buttonCursor: &#39;hand&#39;, // 鼠标指针悬停在按钮上的样子
  
buttonImage: null, // 浏览按钮的图片的路径
  
buttonText: &#39;选择文件&#39;, // 浏览按钮的文本
  
checkExisting: false, // 文件上传重复性检查程序,检查即将上传的文件在服务器端是否已存在,存在返回1,不存在返回0
  
debug: false, // 如果设置为true则表示启用SWFUpload的调试模式
  
fileObjName: &#39;Filedata&#39;, // 文件上传对象的名称,如果命名为&#39;the_files&#39;,PHP程序可以用$_FILES[&#39;the_files&#39;]来处理上传的文件对象
  
fileSizeLimit: &#39;5MB&#39;, // 上传文件的大小限制 ,如果为整数型则表示以KB为单位的大小,如果是字符串,则可以使用(B, KB, MB, or GB)为单位,比如&#39;2MB&#39;;如果设置为0则表示无限制
  
fileTypeDesc: &#39;支持的格式:&#39;, // 这个属性值必须设置fileTypeExts属性后才有效,用来设置选择文件对话框中的提示文本,如设置fileTypeDesc为“请选择rar doc pdf文件”
  
fileTypeExts: &#39;*.*&#39;, // 设置可以选择的文件的类型,格式如:&#39;*.doc;*.pdf;*.rar&#39;
  
height: 24, // 设置浏览按钮的高度 ,默认值
  
itemTemplate: false, // 用于设置上传队列的HTML模版,可以使用以下标签:instanceID – Uploadify实例的ID fileID – 列队中此文件的ID,或者理解为此任务的ID fileName – 文件的名称 fileSize – 当前上传文件的大小 插入模版标签时使用格式如:${fileName}
  
method: &#39;post&#39;, // 提交方式Post或Get
  
multi: true, // 设置为true时可以上传多个文件
  
formData: { &#39;action&#39;: &#39;upload&#39; }, // AnJSON格式上传每个文件的同时提交到服务器的额外数据,可在&#39;onUploadStart&#39;事件中使用&#39;settings&#39;方法动态设置
  
preventCaching: true, // 如果为true,则每次上传文件时自动加上一串随机字符串参数,防止URL缓存影响上传结果
  
progressData: &#39;percentage&#39;, // 设置上传进度显示方式,percentage显示上传百分比,speed显示上传速度
  
listID: false, // 设置附件列表容器DOM元素的ID
  
queueID: false, // 设置上传队列容器DOM元素的ID,如果为false则自动生成一个队列容器
  
queueSizeLimit: 999, // 队列最多显示的任务数量,如果选择的文件数量超出此限制,将会出发onSelectError事件。注意此项并非最大文件上传数量,如果要限制最大上传文件数量,应设置uploadLimit
  
removeCompleted: false, // 是否自动将已完成任务从队列中删除,如果设置为ture则会从队列中移除
  
removeTimeout: 3, // 如果设置了任务完成后自动从队列中移除,则可以规定从完成到被移除的时间间隔
  
requeueErrors: false, // 如果设置为true,则单个任务上传失败后将返回错误,并重新加入任务队列上传
  
successTimeout: 30, // 文件上传成功后服务端应返回成功标志,此项设置返回结果的超时时间
  
uploadLimit: 0, // 最大上传文件数量,如果达到或超出此限制将会触发onUploadError事件
  
width: 75, // 设置文件浏览按钮的宽度
Copy after login


设置的事件:

onDialogClose : function(swfuploadifyQueue) {//当文件选择对话框关闭时触发
  if( swfuploadifyQueue.filesErrored > 0 ){
  alert( &#39;添加至队列时有&#39;
  +swfuploadifyQueue.filesErrored
  +&#39;个文件发生错误n&#39;
  +&#39;错误信息:&#39;
  +swfuploadifyQueue.errorMsg
  +&#39;n选定的文件数:&#39;
  +swfuploadifyQueue.filesSelected
  +&#39;n成功添加至队列的文件数:&#39;
  +swfuploadifyQueue.filesQueued
  +&#39;n队列中的总文件数量:&#39;
  +swfuploadifyQueue.queueLength);
  }
}
  
onDialogOpen : function() {//当选择文件对话框打开时触发
  alert( &#39;Open!&#39;);
}
  
  
  
onSelect : function(file) {//当每个文件添加至队列后触发
  alert( &#39;id: &#39; + file.id
  + &#39; - 索引: &#39; + file.index
  + &#39; - 文件名: &#39; + file.name
  + &#39; - 文件大小: &#39; + file.size
  + &#39; - 类型: &#39; + file.type
  + &#39; - 创建日期: &#39; + file.creationdate
  + &#39; - 修改日期: &#39; + file.modificationdate
  + &#39; - 文件状态: &#39; + file.filestatus);
}
  
  
  
onSelectError : function(file,errorCode,errorMsg) {//当文件选定发生错误时触发
  alert( &#39;id: &#39; + file.id
  + &#39; - 索引: &#39; + file.index
  + &#39; - 文件名: &#39; + file.name
  + &#39; - 文件大小: &#39; + file.size
  + &#39; - 类型: &#39; + file.type
  + &#39; - 创建日期: &#39; + file.creationdate
  + &#39; - 修改日期: &#39; + file.modificationdate
  + &#39; - 文件状态: &#39; + file.filestatus
  + &#39; - 错误代码: &#39; + errorCode
  + &#39; - 错误信息: &#39; + errorMsg);
}
  
  
  
onQueueComplete : function(stats) {//当队列中的所有文件全部完成上传时触发
  alert( &#39;成功上传的文件数: &#39; + stats.successful_uploads
  + &#39; - 上传出错的文件数: &#39; + stats.upload_errors
  + &#39; - 取消上传的文件数: &#39; + stats.upload_cancelled
  + &#39; - 出错的文件数&#39; + stats.queue_errors);
}
  
  
  
onUploadComplete : function(file,swfuploadifyQueue) {//队列中的每个文件上传完成时触发一次
  alert( &#39;id: &#39; + file.id
  + &#39; - 索引: &#39; + file.index
  + &#39; - 文件名: &#39; + file.name
  + &#39; - 文件大小: &#39; + file.size
  + &#39; - 类型: &#39; + file.type
  + &#39; - 创建日期: &#39; + file.creationdate
  + &#39; - 修改日期: &#39; + file.modificationdate
  + &#39; - 文件状态: &#39; + file.filestatus
  + &#39; - 出错的文件数: &#39; + swfuploadifyQueue.filesErrored
  + &#39; - 错误信息: &#39; + swfuploadifyQueue.errorMsg
  + &#39; - 要添加至队列的数量: &#39; + swfuploadifyQueue.filesSelected
  + &#39; - 添加至对立的数量: &#39; + swfuploadifyQueue.filesQueued
  + &#39; - 队列长度: &#39; + swfuploadifyQueue.queueLength);
}
  
  
  
onUploadError : function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {//上传文件出错是触发(每个出错文件触发一次)
  alert( &#39;id: &#39; + file.id
  + &#39; - 索引: &#39; + file.index
  + &#39; - 文件名: &#39; + file.name
  + &#39; - 文件大小: &#39; + file.size
  + &#39; - 类型: &#39; + file.type
  + &#39; - 创建日期: &#39; + file.creationdate
  + &#39; - 修改日期: &#39; + file.modificationdate
  + &#39; - 文件状态: &#39; + file.filestatus
  + &#39; - 错误代码: &#39; + errorCode
  + &#39; - 错误描述: &#39; + errorMsg
  + &#39; - 简要错误描述: &#39; + errorString
  + &#39; - 出错的文件数: &#39; + swfuploadifyQueue.filesErrored
  + &#39; - 错误信息: &#39; + swfuploadifyQueue.errorMsg
  + &#39; - 要添加至队列的数量: &#39; + swfuploadifyQueue.filesSelected
  + &#39; - 添加至对立的数量: &#39; + swfuploadifyQueue.filesQueued
  + &#39; - 队列长度: &#39; + swfuploadifyQueue.queueLength);
}
  
  
  
onUploadProgress : function(file,fileBytesLoaded,fileTotalBytes,
queueBytesLoaded,swfuploadifyQueueUploadSize) {//上传进度发生变更时触发
alert( &#39;id: &#39; + file.id
  + &#39; - 索引: &#39; + file.index
  + &#39; - 文件名: &#39; + file.name
  + &#39; - 文件大小: &#39; + file.size
  + &#39; - 类型: &#39; + file.type
  + &#39; - 创建日期: &#39; + file.creationdate
  + &#39; - 修改日期: &#39; + file.modificationdate
  + &#39; - 文件状态: &#39; + file.filestatus
  + &#39; - 当前文件已上传: &#39; + fileBytesLoaded
  + &#39; - 当前文件大小: &#39; + fileTotalBytes
  + &#39; - 队列已上传: &#39; + queueBytesLoaded
  + &#39; - 队列大小: &#39; + swfuploadifyQueueUploadSize);
}
  
  
  
onUploadStart: function(file) {//上传开始时触发(每个文件触发一次)
  alert( &#39;id: &#39; + file.id
  + &#39; - 索引: &#39; + file.index
  + &#39; - 文件名: &#39; + file.name
  + &#39; - 文件大小: &#39; + file.size
  + &#39; - 类型: &#39; + file.type
  + &#39; - 创建日期: &#39; + file.creationdate
  + &#39; - 修改日期: &#39; + file.modificationdate
  + &#39; - 文件状态: &#39; + file.filestatus );
}
  
onUploadSuccess : function(file,data,response) {//上传完成时触发(每个文件触发一次)
  alert( &#39;id: &#39; + file.id
  + &#39; - 索引: &#39; + file.index
  + &#39; - 文件名: &#39; + file.name
  + &#39; - 文件大小: &#39; + file.size
  + &#39; - 类型: &#39; + file.type
  + &#39; - 创建日期: &#39; + file.creationdate
  + &#39; - 修改日期: &#39; + file.modificationdate
  + &#39; - 文件状态: &#39; + file.filestatus
  + &#39; - 服务器端消息: &#39; + data
  + &#39; - 是否上传成功: &#39; + response);
  
}
Copy after login

5、最后奉上Demo:FileUpload

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C# as a Versatile .NET Language: Applications and Examples C# as a Versatile .NET Language: Applications and Examples Apr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Apr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# and the .NET Runtime: How They Work Together C# and the .NET Runtime: How They Work Together Apr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET: Building Applications with the .NET Ecosystem C# .NET: Building Applications with the .NET Ecosystem Apr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

.NET Framework vs. C#: Decoding the Terminology .NET Framework vs. C#: Decoding the Terminology Apr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# .NET Development: A Beginner's Guide to Getting Started C# .NET Development: A Beginner's Guide to Getting Started Apr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

See all articles