BootStrap Progressbar 實現(xiàn)大文件上傳的進度條的實例代碼

字號:


    這篇文章主要介紹了BootStrap Progressbar 實現(xiàn)大文件上傳的進度條的實例代碼的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    1.首先實現(xiàn)大文件上傳,如果是幾兆或者幾十兆的文件就用基本的上傳方式就可以了,但是如果是大文件上傳的話最好是用分片上傳的方式。我這里主要是使用在客戶端進行分片讀取到服務(wù)器段,然后保存,到了服務(wù)器段讀取完了之后將分片數(shù)據(jù)進行組合。
    2.前端代碼如下:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadTest2.aspx.cs" Inherits="Html5UploadTest.UploadTest2" %>
    <html lang="zh-CN">
    <head>
    <meta charset="utf-8">
    <title>HTML5大文件分片上傳示例</title>
    <script src="Scripts/jquery-1.8.2.js"></script>
    <link href="bootstrap-progressbar/bootstrap-progressbar-3.3.4.css" rel="stylesheet" />
    <script src="bootstrap-progressbar/bootstrap-progressbar.js"></script>
    <%--<link href="JqueryUI/jquery-ui.css" rel="stylesheet" />
    <script src="JqueryUI/jquery-ui.js"></script>--%>
    <script>
    function uploadFile() {
    $("#upload").attr("disabled", "disabled");
    var file = $("#file")[0].files[0], //文件對象
    fileNum = $("#file")[0].files[0].length,
    name = file.name, //文件名
    size = file.size, //總大小
    succeed = 0;
    var shardSize = 2 * 1024 * 1024, //以2MB為一個分片
    shardCount = Math.ceil(size / shardSize); //總片數(shù)
    $('.progress .progress-bar').attr('data-transitiongoal', 0).progressbar({ display_text: 'fill' });
    for (var i = 0; i < shardCount; ++i) {
    //計算每一片的起始與結(jié)束位置
    var start = i * shardSize,
    end = Math.min(size, start + shardSize);
    //構(gòu)造一個表單,F(xiàn)ormData是HTML5新增的
    var form = new FormData();
    form.append("data", file.slice(start, end)); //slice方法用于切出文件的一部分
    form.append("name", name);
    form.append("total", shardCount); //總片數(shù)
    form.append("index", i + 1); //當(dāng)前是第幾片
    //Ajax提交
    $.ajax({
    url: "Upload.ashx",
    type: "POST",
    data: form,
    async: true, //異步
    processData: false, //很重要,告訴jquery不要對form進行處理
    contentType: false, //很重要,指定為false才能形成正確的Content-Type
    success: function () {
    ++succeed;
    $("#output").text(succeed + " / " + shardCount);
    var percent = ((succeed / shardCount).toFixed(2)) * 100;
    updateProgress(percent);
    if (succeed == shardCount) {
    $("#upload").removeAttr("disabled");
    }
    }
    });
    }
    }
    function progress(percent, $element) {
    var progressBarWidth = percent * $element.width() / 100;
    $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + "% ");
    }
    //$(document).ready(function () {
    // $('.progress .progress-bar').progressbar({ display_text: 'fill' });
    //});
    function updateProgress(percentage) {
    $('.progress .progress-bar').attr('data-transitiongoal', percentage).progressbar({ display_text: 'fill' });
    }
    </script>
    </head>
    <body>
    <input type="file" id="file" />
    <button id="upload" onclick="uploadFile();">上傳</button>
    <span id="output">等待</span>
    <div>
    <div id="progressBar" role="progressbar" data-transitiongoal=""></div>
    </div>
    </body>
    </html>
    3. 后臺一般處理程序如下:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    namespace Html5UploadTest
    {
    /// <summary>
    /// Summary description for Upload
    /// </summary>
    public class Upload : IHttpHandler
    {
    public void ProcessRequest(HttpContext context)
    {
    context.Response.ContentType = "text/plain";
    try
    {
    //從Request中取參數(shù),注意上傳的文件在Requst.Files中
    string name = context.Request["name"];
    int total = Convert.ToInt32(context.Request["total"]);
    int index = Convert.ToInt32(context.Request["index"]);
    var data = context.Request.Files["data"];
    //保存一個分片到磁盤上
    string dir = context.Request.MapPath("~/temp");
    string file = Path.Combine(dir, name + "_" + index);
    data.SaveAs(file);
    //如果已經(jīng)是最后一個分片,組合
    //當(dāng)然你也可以用其它方法比如接收每個分片時直接寫到最終文件的相應(yīng)位置上,但要控制好并發(fā)防止文件鎖沖突
    if (index == total)
    {
    file = Path.Combine(dir, name);
    //byte[] bytes = null;
    using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate))
    {
    for (int i = 1; i <= total; ++i)
    {
    string part = Path.Combine(dir, name + "_" + i);
    //bytes = System.IO.File.ReadAllBytes(part);
    //fs.Write(bytes, 0, bytes.Length);
    //bytes = null;
    System.IO.File.Delete(part);
    fs.Close();
    }
    }
    }
    }
    catch (Exception)
    {
    throw;
    }
    //返回是否成功,此處做了簡化處理
    //return Json(new { Error = 0 });
    }
    public bool IsReusable
    {
    get
    {
    return false;
    }
    }
    }
    }
    4.當(dāng)然了后臺還需要一些異常處理或者斷電續(xù)傳的工作要做,待續(xù)。。。
    以上所述是小編給大家介紹的BootStrap Progressbar 實現(xiàn)大文件上傳的進度條的實例代碼,希望對大家有所幫助