实现了上传过程中的实时进度条

以下是我项目中实现的方法,实现了上传过程中的实时进度条,你直接拿去用肯定是不行的,不过可以作为参考 private void btnRefresh_Click(object sender, System.EventArgs e) { FileUploadThread fut = (FileUploadThread) Session["FileUploadThread"]; if (!fut.Uploaded) { litRefreshJS.Text = String.Format("<script>setTimeout(/"{0}/", {1});</script>", Page.GetPostBackClientEvent(btnRefresh, ""), RefreshTime); lblProgress.Text = String.Format("已上传:{0} 总容量:{1} bytes ({2} %)", fut.BytesRead, fut.Length,fut.strPercent); panProgressBar.Width = 3 * fut.Percent; } else { if (fut.Exception == null) { //文件上传成功 string path = this.lblFilename.Text; FilePath = MapPath("/websmoa/SMAdmin/Upload/UploadTemp/");//临时文件路径 FilePath = FilePath + path; Files.UserName = Session["EmpName"].ToString(); FilePath1 = MapPath("/websmoa/Upload/" + Files.UserName + @"/" + path); File.Copy(FilePath,FilePath1); try { //删除临时文件 File.Delete(FilePath); } catch { } if(AddFile())//将文件信息添加到数据库 { FindUseHDCap(); FindSpareHDCap(); this.LblMessage.Text = "<script>alert('文件上传成功');</script>"; } BindFile("",1); } else { lblResult.Text = String.Format("上载文件错误,错误信息如下: {0}
{1}", fut.Exception.GetType(), fut.Exception.Message); } pageMode = PageMode.Result; } } private void ImgBtnUpLoad_Click(object sender, System.Web.UI.ImageClickEventArgs e) { this.pan1.Visible = true; Files.UserName = Session["EmpName"].ToString(); FilePath = theFile.PostedFile.FileName;//取得上传文件完整路径 string FileName = FilePath.Substring(FilePath.LastIndexOf("//")+1);//取得上传文件名和扩展名 FilePath = Server.MapPath("/websmoa/UpLoad/"+ Files.UserName); if (theFile.PostedFile.ContentLength==0) { this.LblMessage.Text = "<script>alert('请选择您要上传的文件')</script>"; return; } this.Label1.Text = Convert.ToString(theFile.PostedFile.ContentLength); this.Label2.Text = this.edInfo.Text; lblFilename.Text = Path.GetFileName(theFile.PostedFile.FileName); lblProgress.Text = String.Format("{0} of {1} bytes (0 %)", 0, theFile.PostedFile.InputStream.Length); string dir = MapPath("/websmoa/upload/"+Files.UserName+@"/"); string Class = this.DDLstFileClassName.SelectedValue;//获取用户选择的文件分类 if (!Directory.Exists(dir))//判断存放上传文件的文件夹是否存在 { Directory.CreateDirectory(dir);//创建存放上传文件的文件夹 } // string FilePath1 = FilePath + Emp.UserName + @"/" + FileName; string FilePath1 = dir + FileName; if(File.Exists(FilePath1)) { this.LblMessage.Text = "<script>alert('已存在同名文件,请修改文件名然后重新上传');</script>"; return; } if(!CheckFileSize(FilePath)) { this.LblMessage.Text = "<script>alert('您的网络硬盘空间不足');</script>"; } else { dir = MapPath("/websmoa/SMAdmin/Upload/UploadTemp/"); Session["FileUploadThread"] = new FileUploadThread(dir + lblFilename.Text, theFile.PostedFile.InputStream); pageMode = PageMode.Uploading; } } public PageMode pageMode { get { object o = ViewState["pageMode"]; return (o==null) ? PageMode.UploadForm : (PageMode) o; } set { ViewState["pageMode"] = value; switch (value) { case PageMode.UploadForm: panResult.Visible = panInfo.Visible = !(panUpload.Visible = true); break; case PageMode.Uploading: litRefreshJS.Text = String.Format("<script>setTimeout(/"{0}/", {1});</script>", Page.GetPostBackClientEvent(btnRefresh, ""), RefreshTime); panResult.Visible = panUpload.Visible = !(panInfo.Visible = true); panProgressBar.Width = 0; break; case PageMode.Result: litRefreshJS.Text = ""; Session.Remove("FileUploadThread"); panUpload.Visible = panInfo.Visible = !(panResult.Visible = true); break; } } } public class FileUploadThread { private long _bytesRead; private Thread _tID; private string _filename; private Stream _stream; private bool _uploaded; private Exception _exception; /// /// How many bytes has been uploaded. /// public long BytesRead { get { return _bytesRead; } } /// /// Length of data to upload /// public long Length { get { return _stream.Length; } } /// /// Determine upload was finished /// public bool Uploaded { get { return _uploaded; } } /// /// How many percent has been uploaded /// public int Percent { get { return (int) ((BytesRead * 100) / Length); } } //精确到小数点后两位(文件数据长度) public string strPercent { get { long longPer = (BytesRead * 100) / Length; string strPer = longPer.ToString(); if(strPer != "0" && (strPer.Length - strPer.IndexOf(".") -1) >= 2 ) { strPer = strPer.Substring(0,strPer.IndexOf(".") + 3);//string strPer } return strPer; } } /// /// Exception object, is there was an exception, otherwise: null. /// public Exception Exception { get { return _exception; } } /// /// Class contructor. /// Initialize fields and create uploading thread. /// /// File's name, with the path, to save /// Upload data's stream (ex. .PostedFile.InputStream) public FileUploadThread(string filename, Stream stream) { _filename = filename; _stream = stream; _uploaded = false; _exception = null; _tID = new Thread(new ThreadStart(uploadThread) ); _tID.Start(); } /// /// Cancel upload's /// public void Cancel() { _tID.Abort(); } /// /// Main thread procedure /// private void uploadThread() { byte[] b = new byte[4096]; int read = 0; try { using (FileStream fs = new FileStream(_filename, FileMode.Create)) { while ((read = _stream.Read(b, 0, b.Length)) > 0) { fs.Write(b, 0, read); _bytesRead += read; System.Threading.Thread.Sleep(100); } } } catch (Exception ex) { _exception = ex; } _uploaded = true; } } 来自:skyhits2008(隐龙绝唱)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值