您的位置:首页 > 编程语言 > ASP

ASP.Net上传文件带进度条、显示剩余时间!

2010-07-09 18:06 691 查看
近段时间因为开发隐私存储网站,采用ASP.Net 2.0在处理上传文件,因为上传的文件比较大,为了改善用户体验,所以自己重写了ASP.Net 的标准上传控件,实现显示进度条,百分比,平均速度,剩余时间,最小化后台运行等功能!

上传文件运行界面:



部份核心代码,需要的朋友根据实际情况修改:

前台处理HTML:UpLoadFile.aspx


程序代码

<%@ Page Language="C#" AutoEventWireup="true" Inherits="WDMM.Web.UpLoad.UpLoadFile" %>
<!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>
<link href="/css/index.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" language="javascript" src="/Script/Prototype.js"></script>
<script type="text/javascript" language="javascript" src="/Script/Common.js"></script>
<script type="text/javascript" language="javascript">
//<![CDATA[
var url = 'progress.aspx?UploadID=<%=Request.QueryString["UploadID"]%>';
//]]>
</script>
</head>
<body>
<div class="mContent">
<div class="scwj">
<form id="upform" method="post" enctype="multipart/form-data" runat="server">
<input id="upload" name="upload" type="hidden" value="no" runat="server" />
<p> <b>选择分类:</b>
<select name="class" style="font-size: 12px;">
<asp:Repeater ID="RepeaterClass" runat="server">
<ItemTemplate>
<option value="<%# Eval("id") %>"> <%# Eval("name") %> </option>
</ItemTemplate>
</asp:Repeater>
</select>
<input type="button" class="tjfl" onclick="Util.classdisplay('01');" />
</p>
<p id="newclass" style="display: none;">
<input name="classtext" type="text" maxlength="30" />
<input name="classadd" type="button" value="确定" class="tjfl1" onclick="Util.chkclass('01');" />
<input name="classcls" type="button" value="取消" class="tjfl2" onclick="Util.clearclass();" />
</p>
<p> </p>
<p> <b>上传:</b></p>
<p id="MyFile">
<input type="file" size="50" name="File" />
</p>
<p>
<input type="button" value="增加文件" class="inputaa" onclick="Files.adds();" />
</p>
<br />
<p> 注:单个上传文件大小,不能超过100MB;每次最多可以上传5个文件。</p>
<br />
<p>
<input type="button" value="重新选择" class="inputaa" onclick="Files.resets();" />
<input type="button" value="开始上传" class="inputaa" onclick="Files.submits();" />
</p>
</form>
</div>
</div>
</body>
</html>

前台处理代码:UpLoadFile.aspx.cs


程序代码

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using WDMM.Common;
using WDMM.Data.SqlServer;
using WDMM.Web.UpLoad;

namespace WDMM.Web.UpLoad
{
public partial class UpLoadFile : WDMM.Common.BasePage
{
private string sFilesserver, sFilepath = "";

protected void Page_Load(object sender, EventArgs e)
{
Utils.GetiFrameLogin();
if (Utils.GetRequestQueryString("UploadID") == "")
{
Response.Redirect("UpLoadFile.aspx?UploadID=" + Utils.GetGuid());
}
Cookies ck = new Cookies();
this.GetFoldersid(ck.Id);
if (Utils.GetRequestForm("upload") == "yes")
{
if (ck.Onlock != "True")
{
sFilesserver = ConfigurationManager.AppSettings["FileServer"].ToString();
sFilepath = HttpContext.Current.Request.MapPath("/File/" + ck.Id + "/");
if (Utils.DirectoryExists(sFilepath))
{
this.SaveFile(ck.Id, ck.Email);
}
}
else
{
StringBuilder java = new StringBuilder();
java.AppendLine("parent.Up.revert();");
java.AppendLine("setTimeout(\"window.location.href = 'UpLoadFile.aspx';\", 1000);");
Utils.javaFunction("您存储空间已被锁定,请先升级!", java.ToString());
}
}
}

/// <summary>
/// 文件夹编号
/// </summary>
private string Foldersid
{
get { return Utils.GetRequestForm("class"); }
set { Foldersid = value; }
}

/// <summary>
/// 获取用户文件夹
/// </summary>
/// <param name="userid"></param>
private void GetFoldersid(string userid)
{
Repeater RepeaterClass;
RepeaterClass = (Repeater)Page.FindControl("RepeaterClass");
using (DataTable dt = DataProvider.GetUserClass(1, userid))
{
if (dt.Rows.Count > 0)
{
RepeaterClass.DataSource = dt;
RepeaterClass.DataBind();
}
}
}

/// <summary>
/// 保存上传文件
/// </summary>
/// <param name="userid"></param>
/// <param name="email"></param>
private void SaveFile(string userid, string email)
{
double disksize, spentsize = 0;
HttpFileCollection files = Request.Files;
try
{
StringBuilder sb = new StringBuilder();
int i = 1;
for (int iFile = 0; iFile < files.Count; iFile++)
{
HttpPostedFile postedFile = files[iFile];
string fileName = Path.GetFileName(postedFile.FileName);
string Extension = Path.GetExtension(postedFile.FileName);
if (Extension != "")
{
double sFilesize = postedFile.ContentLength;
if (Utils.GetFileSizeMB(sFilesize) > 100)
{
sb.Append(i.ToString() + "、文件“" + fileName + "” 超过 100MB 限制,跳过此文件。\\r\\n");
i++;
}
else if (sFilesize < 1)
{
sb.Append(i.ToString() + "、文件“" + fileName + "” 小于 0KB 限制,跳过此文件。\\r\\n");
i++;
}
else
{
using (DataTable dt = DataProvider.GetUserLoginInfo(email))
{
if (dt.Rows.Count > 0)
{
disksize = Convert.ToDouble(dt.Rows[0]["disksize"].ToString());
spentsize = disksize - Convert.ToDouble(dt.Rows[0]["spentsize"].ToString());
}
}
if (sFilesize < spentsize)
{
string sFilename = Guid.NewGuid().ToString();
Fileinfo fi = new Fileinfo();
fi.Userid = userid;
fi.Foldersid = Foldersid;
fi.Extension = Extension;
fi.FileName = fileName;
fi.Filesize = sFilesize.ToString();
fi.Fileserver = sFilesserver;
fi.Diskpath = sFilepath + sFilename + Extension;
postedFile.SaveAs(fi.Diskpath);
if (!DataProvider.SetInFile(fi))
{
Utils.FileDelete(fi.Diskpath);
sb.Append(i.ToString() + "、文件“" + fileName + "”上传失败。\\r\\n");
i++;
}
}
else
{
sb.Append("您的空间已满,请升级再上传!");
break;
}
}
}
}
string para = "ConFileList.aspx";
string strMessage = "温馨提示:";
StringBuilder java = new StringBuilder();
if (sb.Length > 0)
{
strMessage += "\\r\\n\\r\\n" + sb.ToString();
java.AppendLine("parent.Up.revert();");
java.AppendLine("setTimeout(\"window.location.href = 'UpLoadFile.aspx';\", 1000);");
}
else
{
strMessage += "您所选择的文件已全部上传完毕。";
java.AppendLine("parent.Up.Completes('complete," + HttpUploadModule.TotalBytes + "," + HttpUploadModule.TotalBytes + "');");
java.AppendLine("parent.Up.closeup('" + para + "');");
java.AppendLine("setTimeout(\"window.location.href = 'UpLoadFile.aspx';\", 1500);");
}
Utils.javaFunction(strMessage, java.ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message + ex.StackTrace);
}
}
}
}

后台进度条状态:Progress.aspx


程序代码

using System;
using System.Web;
using WDMM.Common;
using WDMM.Web.UpLoad;

namespace WDMM.Web.UpLoad
{
/// <summary>
/// Progress.aspx 页面处理
/// </summary>
public class UploadProgress : WDMM.Common.BasePage
{
private string strResult = "";

protected void Page_Load(object sender, EventArgs e)
{
Progress progress = HttpUploadModule.GetProgress(Utils.GetRequestQueryString("UploadID"), Application);
if (progress != null)
{
if (progress.State == UploadState.ReceivingData)
{
strResult = "send," + progress.ContentLength;
strResult += "," + progress.BytesRead;
}
else if (progress.State == UploadState.Complete)
{
strResult = "complete," + progress.ContentLength;
strResult += "," + progress.BytesRead;
}
else
{
strResult = "error,-1,0";
}
}
Response.Clear();
Response.Write(strResult);
Response.End();
}
}
}

前台Ajax获取上传进度计算相关数据:Common.js


程序代码

var bTimer = 0;
var eTimer = 0;
var mInutes = 0;
var hh = 0;
var mm = 0;
var ss = 0;
var uptime = null;
var Up =
{
Init : function(sType)
{
parent.$('upType').value = sType;
bTimer = new Date();
parent.$('WodemimiUpload').style.display = 'block';
parent.$('Status').innerHTML = '正在分析,请稍候。。。';
setMediacy('WodemimiUpload');
setTimeout('Up.Progress()', 1500);
}
,
Progress : function()
{
var strurl = url + '&type=start&time=' + Ajax.getDatetime();
new Ajax.Request(strurl,
{
method : 'get',
onSuccess : function(sResult)
{
Up.LoadData(sResult.responseText);
}
}
);
}
,
LoadData : function(result)
{
var myArray = result.split(',');
var Percent = 0;
eTimer = new Date();
mInutes = Math.round((eTimer.getTime() - bTimer.getTime()) / 1000);
switch (myArray[0])
{
case 'send' :
Percent = (myArray[2] / myArray[1] * 100).toFixed(2);
parent.$('TotalBytes').innerHTML = GetFileSize(myArray[1], 2);
parent.$('ReadBytes').innerHTML = GetFileSize(myArray[2], 2);
parent.$('Status').innerHTML = '已经上传:';
parent.$('AverageBytes').innerHTML = GetFileSize(myArray[2] / mInutes, 2);
parent.$('SpareHour').innerHTML = GetTimer(myArray[1], myArray[2], mInutes);
parent.$('Percent').style.width = Percent + '%';
parent.$('PercentNumber').innerHTML = Percent + '%';
parent.$('WDMMUpLoad').innerHTML = '<font color="#007500"><strong>显示上传('
+ '<font color="#FF6A00">' + Percent + '%</font>)</strong></font> | ';
break;
case 'complete' :
Up.Complete(result);
Up.clearTime();
break;
case 'error' :
alert(result);
break;
}
uptime = window.setTimeout('Up.Progress()', 1000);
}
,
clearTime : function()
{
if(uptime != null)
{
window.clearTimeout(uptime);
uptime = null;
}
}
,
Complete : function(result)
{
var myArray = result.split(',');
parent.$('TotalBytes').innerHTML = GetFileSize(myArray[1], 2);
parent.$('ReadBytes').innerHTML = '';
parent.$('Status').innerHTML = '上传完毕,加密处理中。。。';
parent.$('SpareHour').innerHTML = '00:00:00';
parent.$('Percent').style.width = '100.00%';
parent.$('PercentNumber').innerHTML = '100.00%';
parent.$('WDMMUpLoad').innerHTML = '<font color="#007500"><strong>显示上传(<font color="#FF6A00">'
+ '100.00%</font>)</strong></font> | ';
setTimeout('parent.Util.condisk();', 2000);
}
,
Completes : function(result)
{
var myArray = result.split(',');
$('TotalBytes').innerHTML = GetFileSize(myArray[1], 2);
$('ReadBytes').innerHTML = '';
$('Status').innerHTML = '上传完毕,加密处理中。。。';
$('SpareHour').innerHTML = '00:00:00';
$('Percent').style.width = '100.00%';
$('PercentNumber').innerHTML = '100.00%';
$('WDMMUpLoad').innerHTML = '<font color="#007500"><strong>显示上传(<font color="#FF6A00">100.00%'
+ '</font>)</strong></font> | ';
}
,
closeup : function(para)
{
switch($('upType').value)
{
case '02' :
setTimeout('menu.active(\'list_02\', \'' + para + '\');', 1500);
break;
case '03' :
setTimeout('menu.active(\'list_03\', \'' + para + '\');', 1500);
break;
case '04' :
setTimeout('menu.active(\'list_04\', \'' + para + '\');', 1500);
break;
}
Up.revert();
}
,
revert : function()
{
$('WodemimiUpload').style.display = 'none';
$('WDMMUpLoad').style.visibility = 'hidden';
$('WDMMInfobar').style.display = 'none';
$('TotalBytes').innerHTML = '0.00 KB';
$('ReadBytes').innerHTML = '0.00 KB';
$('Status').innerHTML = '准备就绪。';
$('SpareHour').innerHTML = '00:00:00';
$('Percent').style.width = '0.00%';
$('PercentNumber').innerHTML = '0.00%';
$('WDMMUpLoad').innerHTML = '<font color="#007500"><strong>显示上传(<font color="#FF6A00">00.00%'
+ '</font>)</strong></font> | ';
$('upType').value = '00';
setTimeout('Util.condisk();', 3000);
}
,
showhideup : function()
{
if($('WodemimiUpload').style.display != 'block')
{
$('WodemimiUpload').style.display = 'block';
$('WDMMUpLoad').style.visibility = 'hidden';
$('WDMMInfobar').style.display = 'none';
}
else
{
$('WodemimiUpload').style.display = 'none';
$('WDMMUpLoad').style.visibility = 'visible';
$('WDMMInfobar').style.display = 'block';
$('WDMMInfobar').style.left = (document.body.clientWidth / 2 - $('WDMMInfobar').clientWidth
/ 2) + 'px';
setTimeout('Up.hideinfo()', 3000);
}
}
,
showup : function()
{
if($('WodemimiUpload').style.display != 'block')
{
$('WodemimiUpload').style.display = 'block';
$('WDMMUpLoad').style.visibility = 'hidden';
$('WDMMInfobar').style.display = 'none';
}
}
,
hideup : function()
{
if($('WodemimiUpload').style.display != 'none')
{
$('WodemimiUpload').style.display = 'none';
$('WDMMUpLoad').style.visibility = 'visible';
$('WDMMInfobar').style.display = 'block';
$('WDMMInfobar').style.left = (document.body.clientWidth / 2 - $('WDMMInfobar').clientWidth
/ 2) + 'px';
setTimeout('Up.hideinfo()', 3000);
}
}
,
hideinfo : function()
{
$('WDMMInfobar').style.display = 'none';
}
,
stopup : function()
{
var sid = 'up_' + $('upType').value + '_tb';
if( ! confirm('温馨提示:我的秘密上传运行中,关闭则需要重新上传。'))
{
return;
}
Up.revert();
menu.refurbish();
setTimeout('menu.deltable(\'' + sid + '\')', 1000);
return;
}
}
;
转自:http://www.80600.net/article.asp?id=163
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: