csharp:asp.net 多文件上傳
http://www.uploadify.com/download/
http://www.cnblogs.com/henw/archive/2012/03/13/2394242.html
https://www.aspsnippets.com/Articles/Implement-Uploadify-jQuery-Plugin-in-ASPNet.aspx
https://www.codeproject.com/tips/340055/upload-files-in-webmatrix-with-uploadify-plugin?pageflow=fluid
https://github.com/haneefputtur/TinyMCE_Uploadify
https://github.com/Code-Fight/.net_uploadify
https://blueimp.github.io/jQuery-File-Upload/angularjs.html
https://github.com/blueimp/jQuery-File-Upload
http://www.c-sharpcorner.com/article/uploading-multiple-files-in-asp-net-mvc/
https://www.codeproject.com/Articles/68374/Upload-Multiple-Files-in-ASP-NET-using-jQuery
示例:
$(document).ready(function() {
$('#fileInput1').fileUpload({
'uploader': 'uploader.swf',//不多讲了
'script': '/AjaxByJQuery/file.do',//处理Action
'cancelImg': 'cancel.png',
'folder': '',//服务端默认保存路径
'scriptData':{'methed':'uploadFile','arg1','value1'},
//向后台传递参数,methed,arg1为参数名,uploadFile,value1为对应的参数值,服务端通过request["arg1"]
'buttonText':'UpLoadFile',//按钮显示文字,不支持中文,解决方案见下
//'buttonImg':'图片路径',//通过设置背景图片解决中文问题,就是把背景图做成按钮的样子
'multi':'true',//多文件上传开关
'fileExt':'*.xls;*.csv',//文件过滤器
'fileDesc':'.xls',//文件过滤器 详解见文档
'onComplete' : function(event,queueID,file,serverData,data){
//serverData为服务器端返回的字符串值
alert(serverData);
}
});
});
scriptData
向后台传递参数,methed,arg1为参数名,uploadFile,value1为对应的参数值,服务端通过request.getP
onComplete中serverData
后台传回前台的值
可选参数
uploadify函数的参数为json格式,可以对json对象的key值的修改来进行自定义的设置,如multi设置为true或false来控制是否可以进行多文件上传,下面就来介绍下这些key值的意思:
uploader : uploadify.swf 文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框,默认值:uploadify.swf。
script : 后台处理程序的相对路径 。默认值:uploadify.php
checkScript :用来判断上传选择的文件在服务器是否存在的后台处理程序的相对路径
fileDataName :设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata
method : 提交方式Post 或Get 默认为Post
scriptAccess :flash脚本文件的访问模式,如果在本地测试设置为always,默认值:sameDomain
folder : 上传文件存放的目录 。
queueID : 文件队列的ID,该ID与存放文件队列的div的ID一致。 进度条放置的位置
queueSizeLimit : 当允许多文件生成时,设置选择文件的个数,默认值:999 。
multi : 设置为true时可以上传多个文件。
auto : 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 。
fileDesc : 这个属性值必须设置fileExt属性后才有效,用来设置选择文件对话框中的提示文本,如设置fileDesc为“请选择rar doc pdf文件”,
fileExt : 设置可以选择的文件的类型,格式如:'*.doc;*.pdf;*.rar' 。
sizeLimit : 上传文件的大小限制 。
simUploadLimit : 允许同时上传的个数 默认值:1 。
buttonText : 浏览按钮的文本,默认值:BROWSE 。
buttonImg : 浏览按钮的图片的路径 。
hideButton : 设置为true则隐藏浏览按钮的图片 。
rollover : 值为true和false,设置为true时当鼠标移到浏览按钮上时有反转效果。
width : 设置浏览按钮的宽度 ,默认值:110。
height : 设置浏览按钮的高度 ,默认值:30。
wmode : 设置该项为transparent 可以使浏览按钮的flash背景文件透明,并且flash文件会被置为页面的最高层。 默认值:opaque 。
cancelImg :选择文件到文件队列中后的每一个文件上的关闭按钮图标
-
上面介绍的key值的value都为字符串或是布尔类型,比较简单,接下来要介绍的key值的value为一个函数,可以在选择文件、出错或其他一些操作的时候返回一些信息给用户。
onInit : 做一些初始化的工作。
onSelect :选择文件时触发,该函数有三个参数
- event:事件对象。
- queueID:文件的唯一标识,由6为随机字符组成。
- fileObj:选择的文件对象,有name、size、creationDate、modificationDate、type 5个属性。
$(document).ready(function() { $("#uploadify").uploadify({ 'uploader': 'JS/jquery.uploadify-v2.1.0/uploadify.swf', 'script': 'UploadHandler.ashx', 'cancelImg': 'JS/jquery.uploadify-v2.1.0/cancel.png', 'folder': 'UploadFile', 'queueID': 'fileQueue', 'auto': false, 'multi': true, 'onInit':function(){alert("1");}, 'onSelect': function(e, queueId, fileObj) { alert("唯一标识:" + queueId + "\r\n" + "文件名:" + fileObj.name + "\r\n" + "文件大小:" + fileObj.size + "\r\n" + "创建时间:" + fileObj.creationDate + "\r\n" + "最后修改时间:" + fileObj.modificationDate + "\r\n" + "文件类型:" + fileObj.type ); } }); });onSelectOnce :在单文件或多文件上传时,选择文件时触发。该函数有两个参数event,data,data对象有以下几个属性:
- fileCount:选择文件的总数。
- filesSelected:同时选择文件的个数,如果一次选择了3个文件该属性值为3。
- filesReplaced:如果文件队列中已经存在A和B两个文件,再次选择文件时又选择了A和B,该属性值为2。
- allBytesTotal:所有选择的文件的总大小。
onCancel : 当点击文件队列中文件的关闭按钮或点击取消上传时触发。该函数有event、queueId、fileObj、data四个参数,前三个参数同onSelect 中的三个参数,data对象有两个属性fileCount和allBytesTotal。
- fileCount:取消一个文件后,文件队列中剩余文件的个数。
- allBytesTotal:取消一个文件后,文件队列中剩余文件的大小。
onClearQueue :当调用函数fileUploadClearQueue时触发。有event和data两个参数,同onCancel 中的两个对应参数。
onQueueFull :当设置了queueSizeLimit并且选择的文件个数超出了queueSizeLimit的值时触发。该函数有两个参数event和queueSizeLimit。
onError :当上传过程中发生错误时触发。该函数有event、queueId、fileObj、errorObj四个参数,其中前三个参数同上,errorObj对象有type和info两个属性。
- type:错误的类型,有三种‘HTTP’, ‘IO’, or ‘Security’
- info:错误的描述
onOpen :点击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列。该函数有event、queueId、fileObj三个参数,参数的解释同上。
onProgress :点击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列,在onOpen之后触发。该函数有 event、queueId、fileObj、data四个参数,前三个参数的解释同上。data对象有四个属性percentage、 bytesLoaded、allBytesLoaded、speed:
- percentage:当前完成的百分比
- bytesLoaded:当前上传的大小
- allBytesLoaded:文件队列中已经上传完的大小
- speed:上传速率 kb/s
onComplete:文件上传完成后触发。该函数有四个参数event、queueId、fileObj、response、data五个参数,前三个参数同上。response为后台处理程序返回的值,在上面的例子中为1或0,data有两个属性fileCount和speed
- fileCount:剩余没有上传完成的文件的个数。
- speed:文件上传的平均速率 kb/s
-
注:fileObj对象和上面讲到的有些不太一样,onComplete 的fileObj对象有个filePath属性可以取出上传文件的路径。
onAllComplete:文件队列中所有的文件上传完成后触发。该函数有event和data两个参数,data有四个属性,分别为:
- filesUploaded :上传的所有文件个数。
- errors :出现错误的个数。
- allBytesLoaded :所有上传文件的总大小。
- speed :平均上传速率 kb/s
https://github.com/rabbitmq/rabbitmq-dotnet-client
https://redis.io/download
https://github.com/fyneworks/multifile
https://github.com/hayageek/jquery-upload-file/
https://www.codeproject.com/tips/531692/multiple-file-upload-using-jquery
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MultiFileDemo.aspx.cs" Inherits="Uploadify.MultiFileDemo" %>
<!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.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery.MultiFile.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" class="multi" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload All"
onclick="btnUpload_Click" />
</div>
</form>
</body>
</html>
/// <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 = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath("uploads") + "\\" +
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/>");
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
自定義用戶上傳控件:
MultipleFileUpload.ascx.cs
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MultipleFileUpload.ascx.cs"
Inherits="MultipleFileUpload" %>
<asp:Panel ID="pnlParent" runat="server" Width="300px" BorderColor="Black" BorderWidth="1px"
BorderStyle="Solid">
<asp:Panel ID="pnlFiles" runat="server" Width="300px" HorizontalAlign="Left">
<asp:FileUpload ID="IpFile" runat="server" />
</asp:Panel>
<asp:Panel ID="pnlListBox" runat="server" Width="292px" BorderStyle="Inset">
</asp:Panel>
<asp:Panel ID="pnlButton" runat="server" Width="300px" HorizontalAlign="Right">
<input id="btnAdd" onclick="javascript:Add();" style="width: 60px" type="button"
runat="server" value="Add" />
<input id="btnClear" onclick="javascript:Clear();" style="width: 60px" type="button"
value="Clear" runat="server" />
<asp:Button ID="btnUpload" OnClientClick="javascript:return DisableTop();" runat="server"
Text="Upload" Width="60px" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblCaption" runat="server" Font-Bold="True" Font-Names="Verdana" Font-Size="XX-Small"
ForeColor="Gray"></asp:Label>
</asp:Panel>
</asp:Panel>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.ComponentModel;
namespace Uploadify
{
/// <summary>
///
/// </summary>
public partial class MultipleFileUpload : System.Web.UI.UserControl
{
//This is Click event defenition for MultipleFileUpload control.
public event MultipleFileUploadClick Click;
/// <summary>
/// The no of visible rows to display.
/// </summary>
private int _Rows = 6;
public int Rows
{
get { return _Rows; }
set { _Rows = value < 6 ? 6 : value; }
}
/// <summary>
/// The no of maximukm files to upload.
/// </summary>
private int _UpperLimit = 0;
public int UpperLimit
{
get { return _UpperLimit; }
set { _UpperLimit = value; }
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
lblCaption.Text = _UpperLimit == 0 ? "Maximum Files: No Limit" : string.Format("Maximum Files: {0}", _UpperLimit);
pnlListBox.Attributes["style"] = "overflow:auto;";
pnlListBox.Height = Unit.Pixel(20 * _Rows - 1);
Page.ClientScript.RegisterStartupScript(typeof(Page), "MyScript", GetJavaScript());
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
// Fire the event.
Click(this, new FileCollectionEventArgs(this.Request));
}
/// <summary>
/// This method is used to generate javascript code for MultipleFileUpload control that execute at client side.
/// </summary>
/// <returns>Javascript as a string object.</returns>
private string GetJavaScript()
{
StringBuilder JavaScript = new StringBuilder();
JavaScript.Append("<script type='text/javascript'>");
JavaScript.Append("var Id = 0;\n");
JavaScript.AppendFormat("var MAX = {0};\n", _UpperLimit);
JavaScript.AppendFormat("var DivFiles = document.getElementById('{0}');\n", pnlFiles.ClientID);
JavaScript.AppendFormat("var DivListBox = document.getElementById('{0}');\n", pnlListBox.ClientID);
JavaScript.AppendFormat("var BtnAdd = document.getElementById('{0}');\n", btnAdd.ClientID);
JavaScript.Append("function Add()");
JavaScript.Append("{\n");
JavaScript.Append("var IpFile = GetTopFile();\n");
JavaScript.Append("if(IpFile == null || IpFile.value == null || IpFile.value.length == 0)\n");
JavaScript.Append("{\n");
JavaScript.Append("alert('Please select a file to add.');\n");
JavaScript.Append("return;\n");
JavaScript.Append("}\n");
JavaScript.Append("var NewIpFile = CreateFile();\n");
JavaScript.Append("DivFiles.insertBefore(NewIpFile,IpFile);\n");
JavaScript.Append("if(MAX != 0 && GetTotalFiles() - 1 == MAX)\n");
JavaScript.Append("{\n");
JavaScript.Append("NewIpFile.disabled = true;\n");
JavaScript.Append("BtnAdd.disabled = true;\n");
JavaScript.Append("}\n");
JavaScript.Append("IpFile.style.display = 'none';\n");
JavaScript.Append("DivListBox.appendChild(CreateItem(IpFile));\n");
JavaScript.Append("}\n");
JavaScript.Append("function CreateFile()");
JavaScript.Append("{\n");
JavaScript.Append("var IpFile = document.createElement('input');\n");
JavaScript.Append("IpFile.id = IpFile.name = 'IpFile_' + Id++;\n");
JavaScript.Append("IpFile.type = 'file';\n");
JavaScript.Append("return IpFile;\n");
JavaScript.Append("}\n");
JavaScript.Append("function CreateItem(IpFile)\n");
JavaScript.Append("{\n");
JavaScript.Append("var Item = document.createElement('div');\n");
JavaScript.Append("Item.style.backgroundColor = '#ffffff';\n");
JavaScript.Append("Item.style.fontWeight = 'normal';\n");
JavaScript.Append("Item.style.textAlign = 'left';\n");
JavaScript.Append("Item.style.verticalAlign = 'middle'; \n");
JavaScript.Append("Item.style.cursor = 'default';\n");
JavaScript.Append("Item.style.height = 20 + 'px';\n");
JavaScript.Append("var Splits = IpFile.value.split('\\\\');\n");
JavaScript.Append("Item.innerHTML = Splits[Splits.length - 1] + ' ';\n");
JavaScript.Append("Item.value = IpFile.id;\n");
JavaScript.Append("Item.title = IpFile.value;\n");
JavaScript.Append("var A = document.createElement('a');\n");
JavaScript.Append("A.innerHTML = 'Delete';\n");
JavaScript.Append("A.id = 'A_' + Id++;\n");
JavaScript.Append("A.href = '#';\n");
JavaScript.Append("A.style.color = 'blue';\n");
JavaScript.Append("A.onclick = function()\n");
JavaScript.Append("{\n");
JavaScript.Append("DivFiles.removeChild(document.getElementById(this.parentNode.value));\n");
JavaScript.Append("DivListBox.removeChild(this.parentNode);\n");
JavaScript.Append("if(MAX != 0 && GetTotalFiles() - 1 < MAX)\n");
JavaScript.Append("{\n");
JavaScript.Append("GetTopFile().disabled = false;\n");
JavaScript.Append("BtnAdd.disabled = false;\n");
JavaScript.Append("}\n");
JavaScript.Append("}\n");
JavaScript.Append("Item.appendChild(A);\n");
JavaScript.Append("Item.onmouseover = function()\n");
JavaScript.Append("{\n");
JavaScript.Append("Item.bgColor = Item.style.backgroundColor;\n");
JavaScript.Append("Item.fColor = Item.style.color;\n");
JavaScript.Append("Item.style.backgroundColor = '#C6790B';\n");
JavaScript.Append("Item.style.color = '#ffffff';\n");
JavaScript.Append("Item.style.fontWeight = 'bold';\n");
JavaScript.Append("}\n");
JavaScript.Append("Item.onmouseout = function()\n");
JavaScript.Append("{\n");
JavaScript.Append("Item.style.backgroundColor = Item.bgColor;\n");
JavaScript.Append("Item.style.color = Item.fColor;\n");
JavaScript.Append("Item.style.fontWeight = 'normal';\n");
JavaScript.Append("}\n");
JavaScript.Append("return Item;\n");
JavaScript.Append("}\n");
JavaScript.Append("function Clear()\n");
JavaScript.Append("{\n");
JavaScript.Append("DivListBox.innerHTML = '';\n");
JavaScript.Append("DivFiles.innerHTML = '';\n");
JavaScript.Append("DivFiles.appendChild(CreateFile());\n");
JavaScript.Append("BtnAdd.disabled = false;\n");
JavaScript.Append("}\n");
JavaScript.Append("function GetTopFile()\n");
JavaScript.Append("{\n");
JavaScript.Append("var Inputs = DivFiles.getElementsByTagName('input');\n");
JavaScript.Append("var IpFile = null;\n");
JavaScript.Append("for(var n = 0; n < Inputs.length && Inputs[n].type == 'file'; ++n)\n");
JavaScript.Append("{\n");
JavaScript.Append("IpFile = Inputs[n];\n");
JavaScript.Append("break;\n");
JavaScript.Append("}\n");
JavaScript.Append("return IpFile;\n");
JavaScript.Append("}\n");
JavaScript.Append("function GetTotalFiles()\n");
JavaScript.Append("{\n");
JavaScript.Append("var Inputs = DivFiles.getElementsByTagName('input');\n");
JavaScript.Append("var Counter = 0;\n");
JavaScript.Append("for(var n = 0; n < Inputs.length && Inputs[n].type == 'file'; ++n)\n");
JavaScript.Append("Counter++;\n");
JavaScript.Append("return Counter;\n");
JavaScript.Append("}\n");
JavaScript.Append("function GetTotalItems()\n");
JavaScript.Append("{\n");
JavaScript.Append("var Items = DivListBox.getElementsByTagName('div');\n");
JavaScript.Append("return Items.length;\n");
JavaScript.Append("}\n");
JavaScript.Append("function DisableTop()\n");
JavaScript.Append("{\n");
JavaScript.Append("if(GetTotalItems() == 0)\n");
JavaScript.Append("{\n");
JavaScript.Append("alert('Please browse at least one file to upload.');\n");
JavaScript.Append("return false;\n");
JavaScript.Append("}\n");
JavaScript.Append("GetTopFile().disabled = true;\n");
JavaScript.Append("return true;\n");
JavaScript.Append("}\n");
JavaScript.Append("</script>");
return JavaScript.ToString();
}
}
/// <summary>
/// EventArgs class that has some readonly properties regarding posted files corresponding to MultipleFileUpload control.
/// </summary>
public class FileCollectionEventArgs : EventArgs
{
private HttpRequest _HttpRequest;
public HttpFileCollection PostedFiles
{
get
{
return _HttpRequest.Files;
}
}
public int Count
{
get { return _HttpRequest.Files.Count; }
}
public bool HasFiles
{
get { return _HttpRequest.Files.Count > 0 ? true : false; }
}
public double TotalSize
{
get
{
double Size = 0D;
for (int n = 0; n < _HttpRequest.Files.Count; ++n)
{
if (_HttpRequest.Files[n].ContentLength < 0)
continue;
else
Size += _HttpRequest.Files[n].ContentLength;
}
return Math.Round(Size / 1024D, 2);
}
}
public FileCollectionEventArgs(HttpRequest oHttpRequest)
{
_HttpRequest = oHttpRequest;
}
}
//Delegate that represents the Click event signature for MultipleFileUpload control.
public delegate void MultipleFileUploadClick(object sender, FileCollectionEventArgs e);
}
WebFileDemo.aspx.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebFileDemo.aspx.cs" Inherits="Uploadify.WebFileDemo" %>
<%@ Register Src="MultipleFileUpload.ascx" TagName="MultipleFileUpload" TagPrefix="uc1" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:MultipleFileUpload ID="MultipleFileUpload1" OnClick="MultipleFileUpload1_Click" runat="server" UpperLimit="3" Rows="6" />
</div>
</form>
</body>
</html>
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MultipleFileUpload1_Click(object sender, FileCollectionEventArgs e)
{
HttpFileCollection oHttpFileCollection = e.PostedFiles;
HttpPostedFile oHttpPostedFile = null;
if (e.HasFiles)
{
for (int n = 0; n < e.Count; n++)
{
oHttpPostedFile = oHttpFileCollection[n];
if (oHttpPostedFile.ContentLength <= 0)
{
continue;
}
else
{
oHttpPostedFile.SaveAs(Server.MapPath("uploads") + "\\" + System.IO.Path.GetFileName(oHttpPostedFile.FileName));
Response.Write("<b>File: </b>" + oHttpPostedFile.FileName + " <b>Size:</b> " + oHttpPostedFile.ContentLength/1024 + "M <b>Type:</b> " + oHttpPostedFile.ContentType + " Uploaded Successfully <br/><br/><br/>");
}
}
}
}
浙公网安备 33010602011771号