一般处理程序、Ajax多图片上传带进度条

时间:2021-04-07 16:01:55

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>文件上传</title>
    <link href="Css/bootstrap.css" rel="stylesheet" />
    <script src="Script/jquery-1.10.2.js"></script>
    <script src="Script/bootstrap.js"></script>
    <script>

function uploadFile() {
            //获取所有的文件控件
            var upfiles = $("input[type=file]");
            //所有文件的分页数
            var filesCountSum = 0;

//设置进度条初始值为0
            $('.progress .progress-bar')[0].style = "width:0%";
            $("#progressBar")[0].innerText = "0%";
            //移除提示框内容、清空文本
            $("#alertBox").removeClass();
            $("#alertBox").text("");
            //设置上传、重置按钮为禁用状态
            $("#upload").addClass("disabled");
            $("#reset").addClass("disabled");

//判断文件删除了几个
            if (upfiles[0].files[0] == undefined || upfiles[1].files[0] == undefined || upfiles[2].files[0] == undefined) {
                $("#alertBox").addClass("alert alert-danger");
                $("#alertBox").text("请上传3个文件");
                $("#upload").removeClass("disabled");
                $("#reset").removeClass("disabled");
            } else {
                //计算所有的文件分片总数
                upfiles.each(function () {
                    size = $(this)[0].files[0].size;

var shardSize = 2 * 1024 * 1024;   //以2MB为一个分片
                    filesCountSum += Math.ceil(size / shardSize);  //总片数

})

var succeed = 0;
                upfiles.each(function () {
                    var file = $(this)[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);  //总片数

//一个文件标签有多个文件的上传
                    //var ss = $(this)[0].files;
                    //for (var i = 0; i < ss.length; i++) {
                    //    console.log(ss[i])
                    //}

for (var i = 0; i < shardCount; ++i) {
                        //计算每一片的起始与结束位置
                        var start = i * shardSize,
                            end = Math.min(size, start + shardSize);
                        //构造一个表单,FormData是HTML5新增的
                        var form = new FormData();
                        form.append("data", file.slice(start, end));  //slice方法用于切出文件的一部分
                        form.append("name", name);
                        form.append("total", shardCount);  //总片数
                        form.append("index", i + 1);        //当前是第几片
                        //Ajax提交
                        $.ajax({
                            url: "/Handlers/UpLoad.ashx",
                            type: "POST",
                            data: form,
                            async: true,        //异步
                            processData: false,  //很重要,告诉jquery不要对form进行处理
                            contentType: false,  //很重要,指定为false才能形成正确的Content-Type
                            success: function () {
                                ++succeed;
                                //显示上传了多少片
                                $("#output").text(succeed + " / " + filesCountSum);
                                var percent = ((succeed / filesCountSum).toFixed(2)) * 100;
                                updateProgress(percent);
                                if (succeed == filesCountSum) {
                                    $("#upload").removeClass("disabled");
                                    $("#reset").removeClass("disabled");
                                    $("#alertBox").addClass("alert alert-success");
                                    $("#alertBox").text("上传成功");
                                }
                            },
                            error: function (req, status, msg) {
                                //如果失败则提示框显示
                                $("#alertBox").addClass("alert alert-danger");
                                $("#alertBox").text(msg);
                            }
                        });
                    }
                })
            }

}
        //用来延时显示更好的效果
        function progress(percent, $element) {
            var progressBarWidth = percent * $element.width() / 100;
            $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + "% ");
        }

//修改精度条的长度显示当前删除到哪里
        function updateProgress(percentage) {
            $('.progress .progress-bar')[0].style = "width:" + percentage + "%";
            $("#progressBar")[0].innerText = percentage + "%";
        }

//重置
        function resetInpu() {
            $("input").each(function () {
                $("#output").text("")
                //标签清空进度条为0
                $(this).val("");
                $('.progress .progress-bar')[0].style = "width:0%";
                $("#progressBar")[0].innerText = "0%";
                //移除提示框内容、清空文本
                $("#alertBox").removeClass();
                $("#alertBox").text("");
            })
        }
    </script>

</head>
<body> 
    <div class="container head">
        <div class="row">
            <div class="panel panel-primary">
                <div class="panel-heading">上传文件</div>
                <div class="panel-body">
                    <!--提示框-->
                    <div class="" id="alertBox"></div>

<div class="input-group">
                        <span class="input-group-addon" id="basic-addon1">文件1</span>
                        <input type="file" id="file" class="form-control" placeholder="Username" aria-describedby="basic-addon1">
                    </div>
                    <br />

<div class="input-group">
                        <span class="input-group-addon" id="basic-addon1">文件2</span>
                        <input type="file" id="file2" class="form-control" placeholder="Username" aria-describedby="basic-addon1">
                    </div>
                    <br />

<div class="input-group">
                        <span class="input-group-addon" id="basic-addon1">文件3</span>
                        <input type="file" id="file3" class="form-control" placeholder="Username" aria-describedby="basic-addon1">
                    </div>
                    <br />

<!-- 进度条 -->
                    <div class="progress">
                        <div id="progressBar" class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                            456456
                        </div>
                    </div>

<!-- 点击按钮 -->
                    <div class="col-md-12 text-center">
                        <button id="upload" onclick="uploadFile()" class="btn btn-primary">上传</button>

<span id="output" style="font-size: 12px">等待</span>

<button id="reset" onclick="resetInpu()" class="btn btn-primary">重置</button>

</div>

<form class="form-horizontal"></form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

<后台>

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

using System.IO;

namespace BaWei.UpLoadFile.Web.Handlers
{
    /// <summary>
    /// 文件上传的一般处理程序
    /// </summary>
    public class UpLoad : IHttpHandler
    {

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                //获取上传文件的名称
                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("/File");
                string file = Path.Combine(dir, name + "_" + index);
                data.SaveAs(file);

//如果已经是最后一个分片,组合
                //接收每个分片时直接写到最终文件的相应位置上
                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 e)
            {
                context.Response.Write(e.Message.ToString());
            }
            //返回是否成功,此处做了简化处理
            //return Json(new { Error = 0 });
        }

public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}