最近做网站用到了上传控件,找到了一个界面比较好看的 Uploadify
看到别人的文章学会使用 。原文地址:
http://doc.chinaunix.net/web/201001/304549.shtml
不是转帖,自己写写自己的。一个完整的解决方案。包括文件上传,文件信息获取和显示,语言:C#
Upload.aspx //上传主页--主要是配置 jquery.uploadify-v2.1.0
html 代码:
<!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 id="Head1" runat="server">
<title>Uploadify</title>
<link href="JS/jquery.uploadify-v2.1.0/example/css/default.css" mce_href="JS/jquery.uploadify-v2.1.0/example/css/default.css" rel="stylesheet" type="text/css" />
<link href="JS/jquery.uploadify-v2.1.0/uploadify.css" mce_href="JS/jquery.uploadify-v2.1.0/uploadify.css" rel="stylesheet" type="text/css" />
<mce:script type="text/javascript" src="JS/jquery.uploadify-v2.1.0/jquery-1.3.2.min.js" mce_src="JS/jquery.uploadify-v2.1.0/jquery-1.3.2.min.js"></mce:script>
<mce:script type="text/javascript" src="JS/jquery.uploadify-v2.1.0/swfobject.js" mce_src="JS/jquery.uploadify-v2.1.0/swfobject.js"></mce:script>
<mce:script type="text/javascript" src="JS/jquery.uploadify-v2.1.0/jquery.uploadify.v2.1.0.min.js" mce_src="JS/jquery.uploadify-v2.1.0/jquery.uploadify.v2.1.0.min.js"></mce:script>
<mce:script type="text/javascript" src="JS/dialog.js" mce_src="JS/dialog.js"></mce:script>
<link href="CSS/dialog.css" mce_href="CSS/dialog.css" rel="stylesheet" type="text/css" />
<mce:script type="text/javascript"><!--
$(document).ready(function()
{
$("#uploadify").uploadify({
'uploader': 'JS/jquery.uploadify-v2.1.0/uploadify.swf', //指定上传控件的主体文件,默认‘uploader.swf’
'script': 'UploadHandler.ashx', //指定服务器端上传处理文件
'cancelImg': 'JS/jquery.uploadify-v2.1.0/cancel.png', //指定取消上传的图片,
'folder': 'UploadFile', //要上传到的服务器路径,默认‘/’
'queueID': 'fileQueue',
'auto': false, //选定文件后是否自动上传,默认false
'multi': true, //是否允许同时上传多文件
'fileDesc' : '允许的类型:doc;ppt;xsl;rar;zip', //出现在上传对话框中的文件类型描述
'fileExt' : '*.rar;*.zip;*.doc;*.ppt;*.xsl', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc
'sizeLimit': 31457280 , //控制上传文件的大小,单位byte 30mb
'queueSizeLimit' :10, //当允许多文件生成时,设置选择文件的个数,默认值:999
'simUploadLimit' :1 , //多文件上传时,同时上传文件数目限制
'buttonText': 'LiuLan' , // 浏览按钮的文本,默认值:BROWSE 。
// 'buttonImg': 浏览按钮的图片的路径 。
// 'hideButton': 设置为true则隐藏浏览按钮的图片 。
// 'rollover':true, // 值为true和false,设置为true时当鼠标移到浏览按钮上时有反转效果。
'width':110, // 设置浏览按钮的宽度 ,默认值:110。
'height':30, // 设置浏览按钮的高度 ,默认值:30。
// 'wmode': 设置该项为transparent 可以使浏览按钮的flash背景文件透明,并且flash文件会被置为页面的最高层。 默认值:opaque 。
/* 上传出错 执行 --针对单个文件 */
'onError' : function (event,queueId,fileObj,errorObj)
{
var iframe=document.getElementById("fileres");
iframe.src="onComplete.aspx?name="+encodeURIComponent(fileObj.name)+"&size="+fileObj.size+"&info="+errorObj.info+"&type="+errorObj.type+"&status="+errorObj.status;
iframe.height=0;
iframe.width=0;
}, /* --注意这的 , 不能忘了,不然出错*/
/* 单个文件上传完成 执行 */
'onComplete':function(event,queueId,fileObj,response,data)
{
var iframe=document.getElementById("fileres");
iframe.src="onComplete.aspx?name="+encodeURIComponent(fileObj.name)+"&size="+fileObj.size+"&speed="+data.speed+"&filecount="+data.fileCount+"&res="+response;
iframe.height=0;
iframe.width=0;
},
/* 全部上传完 执行 */
'onAllComplete' : function(e,data)
{
// var iframe=document.getElementById("fileres");
// iframe.src="OnComplete.aspx?finish=true&succeed="+data.filesUploaded +"&error="+data.errors +"&average="+data.speed +"&allBytes="+data.allBytesLoaded ;
// iframe.height=400;
// iframe.width=600;
// dialog("Welcome Back","iframe:OnComplete.aspx?finish=true&succeed="+data.filesUploaded +"&error="+data.errors +"&average="+data.speed +"&allBytes="+data.allBytesLoaded ,"800px","400px","iframe");
// window.opener("OnComplete.aspx?finish=true&succeed="+data.filesUploaded +"&error="+data.errors +"&average="+data.speed +"&allBytes="+data.allBytesLoaded);
window.location.href="OnComplete.aspx?finish=true&succeed="+data.filesUploaded +"&error="+data.errors +"&average="+data.speed +"&allBytes="+data.allBytesLoaded ;
}
});
});
// --></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div id="fileQueue"></div>
<input type="file" name="uploadify" id="uploadify" />
<p>
<a href="javascript:$('#uploadify').uploadifyUpload()" mce_href="javascript:$('#uploadify').uploadifyUpload()">开始上传</a>|
<a href="javascript:$('#uploadify').uploadifyClearQueue()" mce_href="javascript:$('#uploadify').uploadifyClearQueue()">取消上传</a>
</p>
</form>
<iframe id="fileres" name="fileres" width=0 height=0 ></iframe>
</body>
</html>
后台代码: 无
OnComplete.aspx //文件上传后 处理文件信息
Html 代码
<!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>
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" AutoGenerateColumns="False"
EmptyDataText="错误:没有文件">
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:TemplateField HeaderText="文件名称">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Font-Size="Small" ToolTip='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Type" HeaderText="类型" />
<asp:BoundField DataField="Size" HeaderText="文件大小" />
<asp:BoundField DataField="Speed" HeaderText="上传速度" />
<asp:BoundField DataField="Res" HeaderText="结果" />
<asp:TemplateField HeaderText="课程">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList3_SelectedIndexChanged">
<asp:ListItem>未选择</asp:ListItem>
<asp:ListItem>植物课</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="栏目">
<ItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList4_SelectedIndexChanged">
<asp:ListItem>先选择课程</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="状态">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="30px"
ImageUrl="~/Uploadify/Image/wenhao.png" Width="30px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:Label ID="Label2" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/Teacher/Image/baocun.png" onclick="ImageButton1_Click"
Visible="False" />
<p style="font-size: smaller; color: #FF0000" mce_style="font-size: smaller; color: #FF0000">(警告:未正确配置的文件将被删除!请确认已经配置全部文件)</p></div>
</form>
</body>
</html>
后台代码:
public partial class Uploadify_OnComplete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string name = HttpUtility.UrlDecode(Request.QueryString["name"], Encoding.UTF8);
string finish=Request.QueryString["finish"];
//如果有name 说明是 单文件 调用 可能是 单文件上传成功 或 失败
if (!string.IsNullOrEmpty(name))
{
UploadFile File1 = new UploadFile();
string res = Request.QueryString["res"];
//如果有res 说明是上传成功 没有则上传失败
if (string.IsNullOrEmpty(res))
{
try
{
string strRes="";
string type = Request.QueryString["type"];
if (type == "File Size") strRes = "失败:文件体积太大";
else
if (type == "HTTP") strRes = "失败:网络阻塞" + Request.QueryString["status"];
else strRes = "失败,未知错误";
File1.Name = name;
File1.Type = name.Substring(name.LastIndexOf('.')+1);
File1.Size = Request.QueryString["size"];
File1.Speed = "0";
File1.Res = strRes;
}
catch(Exception e1)
{
Response.Write("传入的数据出错!" + e1.Message);
}
}
else
{
try
{
File1.Name = name;
File1.Type = name.Substring(name.LastIndexOf('.')+1);
File1.Size = Request.QueryString["size"];
File1.Speed = Request.QueryString["speed"];
File1.Res = Request.QueryString["res"];
// File1.ClassName = (string)Session["choseclass"];
File1.Fid = (string)Session["fid"];
File1.Count = Request.QueryString["filecount"];
File1.Time = DateTime.Now.ToString();
}
catch (Exception e1)
{
Response.Write("传入的数据出错!" + e1.Message);
}
}
IList<UploadFile> FileList = new List<UploadFile>();
if (Session["FileList"] == null)
{
Session["FileList"] = FileList;
}
FileList = (IList<UploadFile>)Session["FileList"];
FileList.Add(File1);
Session["FileList"] = FileList;
}
//如果有finish说明是上传完成
else if (!string.IsNullOrEmpty(finish))
{
ImageButton1.Visible = true;
//显示结果
if (Label2.Text != "false")
{
IList<UploadFile> FileList = new List<UploadFile>();
FileList = (IList<UploadFile>)Session["FileList"];
GridView1.DataSource = FileList;
GridView1.DataBind();
Label2.Text = "false";
for (int i = 0; i < GridView1.Rows.Count; i++)
{
string name1 = FileList[i].Name;
if (name1.Length > 13) name1 = name1.Substring(0, 13)+"...";
((Label)GridView1.Rows[i].FindControl("Label1")).Text = name1;
if (FileList[i].Res != "成功")
((DropDownList)GridView1.Rows[i].FindControl("DropDownList3")).Enabled = false;
}
}
Response.Write("成功上传:" + Request.QueryString["succeed"] + "个; 上传失败:" + Request.QueryString["error"]+"个 </br>" );
Response.Write("请在下面配置文件所属课程和栏目!");
}
}
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
string name=ddl.SelectedItem.Value;
GridViewRow gvr = (GridViewRow)ddl.NamingContainer;
int id = gvr.RowIndex;//获得当前行
ddl = (DropDownList)GridView1.Rows[id].FindControl("DropDownList4");
IList<FolderXmlModel> Folder = new List<FolderXmlModel>();
Folder = FolderXml.Read(name);
FolderXmlModel mod = new FolderXmlModel("未选择", "未选择", "");
Folder.Insert(0, mod);
ddl.DataSource = Folder;
ddl.DataTextField = "Id";
ddl.DataValueField = "Id";
ddl.DataBind();
}
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
;
string name =( (DropDownList)sender).SelectedItem.Value;
if (name != "请选择课程")
{
GridViewRow gvr = (GridViewRow)((DropDownList)sender).NamingContainer;
int id = gvr.RowIndex;//获得当前行
((Image)GridView1.Rows[id].FindControl("Image1")).ImageUrl = "Image/duihao.png";
}
}
/// <summary>
/// 保存设置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
IList<UploadFile> FileList = new List<UploadFile>();
FileList = (IList<UploadFile>)Session["FileList"];
Session["FileList"] = null;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
FileList[i].ClassName = ((DropDownList)GridView1.Rows[i].FindControl("DropDownList3")).SelectedItem.Value;//课程
FileList[i].Lanmu = ((DropDownList)GridView1.Rows[i].FindControl("DropDownList4")).SelectedItem.Value;//栏目
}
UploadFileLog.CreatLog(FileList);
FileList = null;
Response.Redirect("Upload.aspx");
}
}
UploadHandler.ashx //接受上传文件并存储
using System;
using System.Web;
public class UploadHandler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
UploadFile uploadfile = TestUploadFile.CreateUploadFile();
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
HttpPostedFile file = context.Request.Files["Filedata"];
string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "//";
if (file != null)
{
if (!System.IO.Directory.Exists(uploadPath))
{
System.IO.Directory.CreateDirectory(uploadPath);
}
file.SaveAs(uploadPath + file.FileName);
TestUploadFile.CloseUploadFile(uploadfile);
//下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
context.Response.Write("1");
}
else
{
context.Response.Write("0");
}
}
public bool IsReusable {
get {
return false;
}
}
}
web.config
</configuration>
TestUploadFile.cs //控制上传 网站同时可以有5个上传线程。
/// <summary>
///TestUploadFile 的摘要说明
/// </summary>
public class TestUploadFile
{
public TestUploadFile()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
private static UploadFile[] Files = new UploadFile[5] { new UploadFile(), new UploadFile(), new UploadFile(), new UploadFile(), new UploadFile()};
/// <summary>
/// 返回空闲的上传对象
/// </summary>
/// <returns></returns>
public static UploadFile CreateUploadFile()
{
xx:
int i = 0;
foreach (UploadFile Fi in Files)
{
i++;
lock (Fi)
{
if (Fi.Enable)
{
Fi.Enable = false;
return Fi;
}
}
}
//如果没有空闲连接,则重新申请
System.Threading.Thread.Sleep(50);
goto xx;
}
/// <summary>
/// 关闭文件对象
/// </summary>
/// <param name="cn"></param>
public static void CloseUploadFile(UploadFile uploadfile)
{
foreach (UploadFile file in Files)
{
if (file == uploadfile)
{
lock (uploadfile)
{
uploadfile.Enable = true;
return;
}
}
}
}
/// <summary>
/// 根据文件名,查找文件对象
/// </summary>
/// <param name="Name"></param>
/// <returns></returns>
public static UploadFile FindUoloadFile(string Name)
{
//循环10次--最多查找两秒钟 因为有时候大文件上传有延时。
//可能客户端显示上传完成,但是服务器还没来得及生成文件
for (int i = 0; i < 10; i++)
{
foreach (UploadFile file in Files)
{
if (file.Name == Name)
{
return file;
}
}
System.Threading.Thread.Sleep(200);
}
return null;
}
}
UploadFile.cs
/// <summary>
///UploadFile 的摘要说明
///文件上传的实体类
/// </summary>
public class UploadFile
{
public UploadFile()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
private string _count = "";
/// <summary>
/// 剩余文件数
/// </summary>
public string Count
{
get { return _count; }
set { _count = value; }
}
private bool _Enable = true;
//上传是否可用--同时最多5文件上传
public bool Enable
{
get
{
return _Enable;
}
set
{
_Enable = value;
}
}
private string _name = "";
/// <summary>
/// 文件名
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _size = "";
/// <summary>
/// 文件大小 kb 、mb自适应
/// </summary>
public string Size
{
get { return _size; }
set
{
double n = double.Parse(value);
if (n < 1024) _size = n + "Bytes";
else if (n < 1048576) _size = (n / 1024).ToString("0.00") + "KB";
else if (n < 1073741824) _size = (n / 1024 / 1024).ToString("0.00") + "MB";
else _size = (n / 1024 / 1024 / 1024).ToString("0.00") + "GB";
}
}
private string _type = "";
/// <summary>
/// 文件类型
/// </summary>
public string Type
{
get { return _type; }
set { _type = value; }
}
private string _classname = "";
/// <summary>
/// 课程名
/// </summary>
public string ClassName
{
get { return _classname; }
set { _classname = value; }
}
private string _fid = "";
/// <summary>
/// 所在文件名
/// </summary>
public string Fid
{
get { return _fid; }
set { _fid = value; }
}
private string _speed = "";
/// <summary>
/// 速度
/// </summary>
public string Speed
{
get { return _speed; }
set
{
if (value=="null") _speed = _size + "/s";
else
{
double n = double.Parse(value);
if (n < 1024) _speed = (n ).ToString("0.00") + "Bytes/s";
else if (n < 1048576 ) _speed = (n / 1024).ToString("0.00") + "KB/s";
else if (n < (double)1073741824) _speed = (n / 1024 / 1024).ToString("0.00") + "MB/s";
else _speed = (n / 1024 / 1024 / 1024).ToString("0.00") + "GB/s";
}
}
}
private string _res = "";
/// <summary>
/// 上传结果
/// </summary>
public string Res
{
get { return _res; }
set {
if (value == "1") _res = "成功";
else if (value == "0") _res = "失败";
else _res = value;
}
}
private string _time = "";
/// <summary>
/// 上传时间
/// </summary>
public string Time
{
get { return _time; }
set { _time = value; }
}
private string _lanmu = "";
/// <summary>
/// 文件所处的栏目--从课程名开始的路径
/// 例如:植物课/授课教案/习题库
/// </summary>
public string Lanmu
{
get { return _lanmu; }
set { _lanmu = value; }
}
}
UploadFileLog.cs
/// <summary>
///UploadFileLog 的摘要说明
/// </summary>
public class UploadFileLog
{
public UploadFileLog()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public static void CreatLog( IList<UploadFile> FileList)
{
}
}