zoukankan      html  css  js  c++  java
  • asp.net 文件下载,多任务并行有进度条 (20121018 15:36)

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RenameDownload.aspx.cs" Inherits="DownloadProxy.RenameDownload" %>
    
    <!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>
        <style type="text/css">
            body
            {
                font-size:12px;
                }
            table
            {
                background-color:Gray;
                }
                
            td
            {
                background-color:White;
                }
        </style>
        <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:scriptmanager runat="server" EnablePageMethods="true"></asp:scriptmanager>
        <script type="text/javascript">
            window.onbeforeunload = function () {
                return false;
            };
    
            //PageMethods.set_timeout(5000);
            PageMethods.set_defaultFailedCallback = "OnFailed";
            
            function OnFailed(ErrorHander) {
                var ErrorMessage = 'Timeout:' + ErrorHander.get_timedOut() + ',Error Message:' + ErrorHander.get_message();
                ErrorMessage = ErrorMessage + ',Exception Type:' + ErrorHander.get_exceptionType() + ',Error Loaction:' + ErrorHander.get_stackTrace();
                alert(ErrorMessage);
            }
    
            function DownloadFile() {
                PageMethods.DownloadFile($("#txtUrl").val(), $("#txtFileName").val(), function (fileHandle) {
    
                    var task = $("#taskPanel").find(".task:last");
                    if (fileHandle > 1) {
                        $(task).clone().appendTo($("#taskPanel"));
                        task = $("#taskPanel").find(".task:last");
                        $(task).find(".taskId").attr("innerHTML", fileHandle);
                        $(task).find(".file").attr("innerHTML", "file");
                        $(task).find(".size").attr("innerHTML", "size");
                        $(task).find(".progress").find("#progressBar").css("width", "5%");
                        $(task).find(".progress").find("#progressLabel").attr("innerHTML", "5%");
                        $(task).find(".status").attr("innerHTML", "status");
                    }
    
                    var interval = setInterval(function () {
                        PageMethods.GetFileDownloadProcess(fileHandle, function (result) {
                            $(task).find(".taskId").attr("innerHTML", result.TaskId);
                            $(task).find(".file").attr("innerHTML", result.FileName);
                            $(task).find(".size").attr("innerHTML", result.FileSize);
                            $(task).find(".progress").find("#progressBar").css("width", result.Progress + "%");
                            $(task).find(".progress").find("#progressLabel").attr("innerHTML", result.Progress + "%");
                            $(task).find(".status").attr("innerHTML", result.Status);
                            if (result.Status == 1) {
                                $(task).find(".download").find("a").bind("click", function () {
                                    window.open("?path=" + encodeURI(result.FilePath));
                                });
                                clearInterval(interval);
                            }
                        });
                    }, 1000);
    
                });
            }
    
            function fillFileName() {
                var url = $("#txtUrl").val();
                if (url != "") {
                    var fileName = url.substr(url.lastIndexOf('/') + 1);
                    $("#txtFileName").val(fileName);
                }
            }
        </script>
        <table cellspacing="0" cellpadding="10">
            <tr>
                <td>
                    <table id="downloadPanel" cellspacing="1" cellpadding="5" width="600px">
                        <tr>
                            <td width="100px">Url:</td>
                            <td width="400px">
                                <textarea id="txtUrl" cols="0" rows="5" style="400px;margin:5px;text-align:left;vertical-align:top;" onchange="fillFileName()">https://download.alipay.com/sec/edit/aliedit.exe</textarea>
                            </td>
                            <td width="100" valign="bottom" align="center" rowspan="2">
                                <input type="button" value="download" runat="server" id="btnDownload" onclick="DownloadFile()" />
                            </td>
                        </tr>
                        <tr>
                            <td>File Name:</td>
                            <td><input style="400px;" type="text" id="txtFileName" size="25" value="aliedit.exe" /></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    <table id="taskPanel" style="background-color:gray" cellpadding="5" cellspacing="1">
                        <tr>
                            <td style="100px;text-align:center;">TaskID</td>
                            <td style="100px;text-align:left;">File</td>
                            <td style="100px;text-align:left;">Size</td>
                            <td style="200px;text-align:left;">Progress</td>
                            <td style="100px;text-align:left;">Status</td>
                            <td style="100px;text-align:left;">Download</td>
                        </tr>
                        <tr class="task">
                            <td style="100px;text-align:center;" class="taskId">&nbsp;</td>
                            <td style="100px;text-align:left;"  class="file">&nbsp;</td>
                            <td style="100px;text-align:left;" class="size">&nbsp;</td>
                            <td style="200px;text-align:left;" class="progress">
                                <table cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td style="175px;">
                                            <div style="height:10px;173px;border:1px solid gray;margin:0px;padding:0px;">
                                                <div id="progressBar" style="height:100%;0%;margin:0px;padding:0px;background-color:Gray;"></div>
                                            </div>    
                                        </td>
                                        <td style="25px;text-align:center;" id="progressLabel">
                                            0%
                                        </td>
                                    </tr>
                                </table>
                                
                            </td>
                            <td style="100px;text-align:left;" class="status">&nbsp;</td>
                            <td style="100px;text-align:left;" class="download"><a href="#">download</a></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Net;
    using System.IO;
    using System.Threading;
    using System.Configuration;
    
    namespace DownloadProxy
    {
        public class Task
        {
            public int TaskId { get; set; }
            public string Url { get; set; }
            public string FilePath { get; set; }
            public string FileName 
            {
                get
                {
                    return new FileInfo(FilePath).Name;
                }
            }
            public long FileSize { get; set; }
            public int Progress { get; set; }
            public int Status { get; set; }
        }
    
        public partial class RenameDownload : System.Web.UI.Page
        {
            public static Dictionary<int,Task> FilesDownloadProcess { get; set; }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["path"]))
                {
                    var path = Request.QueryString["path"];
                    if (!System.IO.File.Exists(path))
                    {
                        Response.End();
                        return;
                    }
                    OutPutFile(path);
                }
    
                if (!IsPostBack)
                {
                    FilesDownloadProcess = new Dictionary<int, Task>();
                }
            }
            
            [System.Web.Services.WebMethod]
            public static int DownloadFile(String remoteFilename, String localFilename)
            {
                var fileHand = FilesDownloadProcess.Count + 1;
                var baseFileName = string.Empty;
                var fileExtension = string.Empty;
                var downloadPath = ConfigurationManager.AppSettings["downloadPath"];
                if (localFilename.Trim() == string.Empty)
                {
                    baseFileName = "001";
                    fileExtension = "";
                }
                else
                {
                    try
                    {
                        var fileInfo = new FileInfo(localFilename);
                        fileExtension = fileInfo.Extension;
                        baseFileName = fileInfo.Name.Substring(0, fileInfo.Name.Length - fileExtension.Length);
                    }
                    catch (Exception)
                    {
                        //throw;
                    }
                }
    
                var filePath = string.Format(@"{0}\{1}", downloadPath, localFilename);
                for (var i = 1; System.IO.File.Exists(filePath); i++)
                {
                    filePath = string.Format(@"{0}\{1}({2}){3}", downloadPath, baseFileName, i, fileExtension);
                }
                localFilename = filePath;
    
                var task = new Task
                {
                    TaskId = fileHand ,
                    Url = remoteFilename ,
                    FilePath = localFilename , 
                    FileSize = 0 ,
                    Progress = 0 ,
                    Status = 0
                };
    
                FilesDownloadProcess.Add(task.TaskId, task);
    
                var thread = new Thread(new ThreadStart(delegate() 
                    {
                        DownloadFileProc(task.Url, task.FilePath, task.TaskId);
                    }));
                thread.Start();
    
                return fileHand;
            }
    
            public static long DownloadFileProc(String remoteFilename, String localFilename,int taskId)
            {
                long bytesProcessed = 0;
    
                Stream remoteStream = null;
                Stream localStream = null;
                WebResponse response = null;
    
                try
                {
                    // Create a request for the specified remote file name
                    var request = (HttpWebRequest)WebRequest.Create(remoteFilename);
                    request.AllowWriteStreamBuffering = true;
                    request.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    request.Proxy = new WebProxy { UseDefaultCredentials = true };
                    request.MaximumResponseHeadersLength = -1;
                    request.Accept = "www/source, text/html, video/mpeg, image/jpeg, image/x-tiff, image/x-rgb, image/x-xbm, image/gif, application/postscript, application/x-gzip, */*, ";
                    request.AllowAutoRedirect = true;
                    request.UserAgent = "TLE Retriever v1.5.8";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Method = "GET";
                    request.Headers.Add("Accept-Language", "zh-cn");
                    request.Headers.Add("Accept-Encoding", "gzip,deflate");
                    request.KeepAlive = true;
                    if (request != null)
                    {
                        response = request.GetResponse();
                        FilesDownloadProcess[taskId].FileSize = response.ContentLength;
    
                        if (response != null)
                        {
                            remoteStream = response.GetResponseStream();
    
                            // Create the local file
                            localStream = File.Create(localFilename);
    
                            // Allocate a 1k buffer
                            byte[] buffer = new byte[1024];
                            int bytesRead;
    
                            // Simple do/while loop to read from stream until
                            // no bytes are returned
                            do
                            {
                                // Read data (up to 1k) from the stream
                                bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
    
                                // Write the data to the local file
                                localStream.Write(buffer, 0, bytesRead);
    
                                // Increment total bytes processed
                                bytesProcessed += bytesRead;
    
                                FilesDownloadProcess[taskId].Progress = (int)(((double)bytesProcessed / (double)FilesDownloadProcess[taskId].FileSize) * 100);
    
                                if (FilesDownloadProcess[taskId].Progress >= 100)
                                {
                                    FilesDownloadProcess[taskId].Status = 1;
                                }
    
                            } while (bytesRead > 0);
                        }
                    }
                }
                catch
                {
                    //throw;
                }
                finally
                {
                    if (response != null) response.Close();
                    if (remoteStream != null) remoteStream.Close();
                    if (localStream != null) localStream.Close();
                }
    
                // Return total bytes processed to caller.
                return bytesProcessed;
            }
    
            public void OutPutFile(string filePath)
            {
                System.IO.Stream iStream = null;
    
                // Buffer to read 10K bytes in chunk:
                byte[] buffer = new Byte[10000];
    
                // Length of the file:
                int length;
    
                // Total bytes to read:
                long dataToRead;
    
                // Identify the file name.
                string filename = System.IO.Path.GetFileName(filePath);
    
                try
                {
                    // Open the file.
                    iStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                                System.IO.FileAccess.Read, System.IO.FileShare.Read);
    
    
                    // Total bytes to read:
                    dataToRead = iStream.Length;
    
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
    
                    // Read the bytes.
                    while (dataToRead > 0)
                    {
                        // Verify that the client is connected.
                        if (Response.IsClientConnected)
                        {
                            // Read the data in buffer.
                            length = iStream.Read(buffer, 0, 10000);
    
                            // Write the data to the current output stream.
                            Response.OutputStream.Write(buffer, 0, length);
    
                            // Flush the data to the HTML output.
                            Response.Flush();
    
                            buffer = new Byte[10000];
                            dataToRead = dataToRead - length;
                        }
                        else
                        {
                            //prevent infinite loop if user disconnects
                            dataToRead = -1;
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Trap the error, if any.
                    Response.Write("Error : " + ex.Message);
                }
                finally
                {
                    if (iStream != null)
                    {
                        //Close the file.
                        iStream.Close();
                    }
                }
    
            }
    
            [System.Web.Services.WebMethod]
            public static Task GetFileDownloadProcess(int fileHandle)
            {
                return FilesDownloadProcess[fileHandle];
            }
        }
    }

  • 相关阅读:
    Solution -「Gym 102798I」Sean the Cuber
    Solution -「Gym 102798K」Tree Tweaking
    Solution -「Gym 102798E」So Many Possibilities...
    Solution -「Gym 102759I」Query On A Tree 17
    Solution -「Gym 102759G」LCS 8
    Solution -「Gym 102759F」Interval Graph
    Solution -「Gym 102759C」Economic One-way Roads
    Solution -「ABC 213G」Connectivity 2
    Solution -「ABC 213H」Stroll
    @WebFilter注入失败
  • 原文地址:https://www.cnblogs.com/nanfei/p/2731388.html
Copyright © 2011-2022 走看看