码迷,mamicode.com
首页 > Windows程序 > 详细

C#实现文件上传进度条

时间:2015-09-29 21:49:59      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

1、前台代码FileProcessBar.aspx:

<%@ page Language="C#" AutoEventWireup="true" CodeFile="FileProcessBar.aspx.cs" EnableEventValidation="false" Inherits="FileProcessBar" %>

<!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 language="javascript" type="text/javascript">
        function checkFile(source, arguments) {
            arguments.IsValid = (document.all["theFile"].value != "");
        } 
</script> 
    <style type="text/css">
       
        .style1
        {
            width: 600px;
        }
       
        .style2
        {
            width: 48px;
        }
        .style3
        {
            width: 81px;
        }
       
     
       
    </style>
</head>
<body>
<form id="form1" runat="server"> 

<table align="center" class="style1">
        <tr>
            <td>
               
<asp:HyperLink id="lnkReload" runat="server" NavigateUrl="FileprocessBar.aspx" 
        Font-Bold="true">重新载入页面</asp:HyperLink>
            </td>
        </tr>
    </table>

<asp:panel id="panUpload" runat="server"> 
<table  align="center" class="style1"> 
<tr> 
<td colspan="2" >请选择你要上载的文件:</td> 
</tr> 
<tr> 
<td align="right" class="style2"  >文件:</td> 
<td > 
    <input id="theFile" style="WIDTH: 100%" type="file" name="theFile" 
        runat="server" />
    </td> 
</tr> 
<tr> 
<td align="right" class="style2"  ></td> 
<td> 
    <asp:CustomValidator ID="cusValTheFile" runat="server" 
        ClientValidationFunction="checkFile" Display="Dynamic" 
        ErrorMessage="你必须选择你上载的&lt;b&gt;文件&lt;/b&gt;。"></asp:CustomValidator>
    </td> 
</tr> 
<tr> 
<td align="right" class="style2"  >描述:</td> 
<td> 
    <asp:TextBox ID="edInfo" runat="server" Width="100%"></asp:TextBox>
    </td> 
</tr> 
<tr> 
<td align="right" class="style2"></td> 
<td> 
    <asp:RequiredFieldValidator ID="reqValInfo" runat="server" 
        ControlToValidate="edInfo" Display="Dynamic" 
        ErrorMessage="文件的 &quot;&lt;b&gt;描述&lt;/b&gt;&quot; 不能为空,请输入一些信息。"></asp:RequiredFieldValidator>
    </td> 
</tr> 
<tr> 
<td align="right" class="style2" ></td> 
<td> 
    <asp:CheckBox ID="chbImportant" runat="server" Text="重要" />
    </td> 
</tr> 
    <tr>
        <td align="right" class="style2" >
        </td>
        <td>
            <asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click" Text="上载" 
                Width="64px" />
        </td>
    </tr>
</table> 
<br/> 
</asp:panel> 
<asp:panel id="panInfo" runat="server"> 
<table align="center" class="style1">
<tr> 
<td align="right" width="100" colspan="2" style="width: 500px; text-align: left"  >
    <asp:LinkButton ID="btnRefresh" runat="server" onclick="btnRefresh_Click" 
        style="text-align: left" Visible="False">上载图像...</asp:LinkButton>
    </td> 
</tr> 
    <tr>
        <td align="right" class="style3" >
            文件名称:</td>
        <td width="400">
            <asp:Label ID="lblFilename" runat="server" Font-Bold="true"></asp:Label>
        </td>
    </tr>
<tr> 
<td align="right" class="style3" >进程条:</td> 
<td width="400" > 
<asp:Label id="lblProgress" runat="server" Font-Bold="True"></asp:Label></td> 
</tr> 
<tr> 
<td align="right" class="style3"  ></td> 
<td width="400" > 
    <asp:Image ID="panProgressBar" runat="server" ImageUrl="~/images/1.JPG" 
        Height="20px" />
    </td> 
</tr> 
<tr> 
<td align="right" class="style3"  ></td> 
<td width="400"> 
<asp:Button id="btnCancel" runat="server" Width="64px" Text="取消" 
        onclick="btnCancel_Click"></asp:Button></td> 
</tr> 
</table> 
</asp:panel> 
<asp:Panel id="panResult" runat="server"> 

    <table align="center" class="style1">
        <tr>
            <td><asp:Label ID="lblResult" runat="server"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <asp:HyperLink ID="lbkReturn" runat="server" NavigateUrl="FileprocessBar.aspx">返回上载页面</asp:HyperLink>
            </td>
        </tr>
    </table>
</asp:Panel> 

<table align="center" class="style1">
    <tr>
        <td>

<asp:Literal id="litRefreshJS" runat="server"></asp:Literal> 
        </td>
    </tr>
</table>
</form> 
</body>
</html>

2、后台代码FileProcessBar.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class FileProcessBar : System.Web.UI.Page
{
    
    
    // determin how often Progress Info will be refreshed 
    const int RefreshTime = 0;

    // determine, which panel to show 
    public enum PageMode { UploadForm, Uploading, Result }
    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:
                    // initialize fields 
                    litRefreshJS.Text = String.Format("<script>setTimeout(\"{0}\", {1});</script>", ClientScript.GetPostBackEventReference( btnRefresh, ""), RefreshTime);
                    panResult.Visible = panUpload.Visible = !(panInfo.Visible = true);
                    panProgressBar.Width = 0;
                    break;
                case PageMode.Result:
                    // result information 
                    litRefreshJS.Text = "";
                    Session.Remove("FileUploadThread");
                    panUpload.Visible = panInfo.Visible = !(panResult.Visible = true);
                    break;
            }
        }
    }

    // how many bytes has been uploaded. 
    public long BytesRead
    {
        get { object o = ViewState["BytesRead"]; return (o == null) ? 0 : (long)o; }
        set { ViewState["BytesRead"] = value; }
    } 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["FileUploadThread"] != null)
            {
                // this users has the session, possible there‘s an unfinished file upload 
                lblResult.Text = "文件正在上载过程中……";
                litRefreshJS.Text = "";
                pageMode = PageMode.Result;
            }
            else pageMode = PageMode.UploadForm;
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (theFile.PostedFile.ContentLength == 0) return;

        lblFilename.Text = Path.GetFileName(theFile.PostedFile.FileName);
        lblProgress.Text = String.Format("{0} of {1} bytes (0 %)", 0, theFile.PostedFile.InputStream.Length);

        string dir = MapPath("files/");
        if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);

        Session["FileUploadThread"] = new FileUploadThread(dir + lblFilename.Text, theFile.PostedFile.InputStream);
        pageMode = PageMode.Uploading; 
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        FileUploadThread fut = (FileUploadThread)Session["FileUploadThread"];
        if (fut != null) fut.Cancel();
        

        lblResult.Text = "上载文件已经被取消!";
        pageMode = PageMode.Result; 
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        FileUploadThread fut = (FileUploadThread)Session["FileUploadThread"];

        if (!fut.Uploaded)
        {
            litRefreshJS.Text = String.Format("<script>setTimeout(\"{0}\", {1});</script>", ClientScript.GetPostBackEventReference(btnRefresh, ""), RefreshTime);
            lblProgress.Text = String.Format("{0} of {1} bytes ({2} %)", fut.BytesRead,fut.Length,fut.Percent);
            panProgressBar.Width = 2 * fut.Percent;
            panProgressBar.Height = 20;

        }
        else
        {
            if (fut.Exception == null)
                lblResult.Text = String.Format("\"<a href=‘files/{0}‘>{0}</a>\" 文件上载成功!<br/>文件是:{1}<br/>描述是:{2}", lblFilename.Text, (chbImportant.Checked) ? "重要的" : "不重要的", edInfo.Text);
            else
                lblResult.Text = String.Format("上载文件错误,错误信息如下: {0}<br>{1}", fut.Exception.GetType(), fut.Exception.Message);

            pageMode = PageMode.Result;
        } 
    }
}

3、类文件FileUploadThread.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.IO;

/// <summary>
///FileUploadThread 的摘要说明
/// </summary>
public class FileUploadThread
{
    private string _filename;
    private Stream _stream;
    private bool _uploaded;
    private Exception _exception;
    private Thread _tID;
    private int _bytesRead;
    private int _length;
    private int  _percent;

    public FileUploadThread(string filename,Stream stream)
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
        _filename = filename;
        _stream = stream;
        _length = (int)_stream.Length;
        _uploaded = false;
        _exception = null;
        _tID = new Thread(new ThreadStart(uploadThread));
        _tID.Start();
        
	}
    public void Cancel()
    {
    }

    public bool Uploaded
    {
        get { return _uploaded; }
        set { _uploaded = value; }
    }

    public Exception Exception
    {
        get { return _exception; }
        set { _exception = value; }
    }

    public int BytesRead
    {
        get { return _bytesRead; }
        set { _bytesRead = value; }
    }
    public int Length
    {
        get { return _length ; }
        set { _length  = value; }
    }
    public int  Percent
    {
        get { return _percent ; }
        set { _percent  = value; }
    }
    private void uploadThread()
    {
        byte[] b=new byte[1024];
        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 ;
                    _percent = (int)(_bytesRead*100 /_length);
                    System.Threading.Thread.Sleep(1000);
                }

            }
        }
        catch(Exception ex){_exception=ex;}
        _uploaded=true ;
    }
}

  

C#实现文件上传进度条

标签:

原文地址:http://www.cnblogs.com/xusy/p/4847368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!