前台代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/bootstrap.js"></script>
<style>
.head {
margin-top: 20px;
}
</style> <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); //总片数 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: "Handler1.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 () {
//如果失败则提示框显示
$("#alertBox").addClass("alert alert-danger");
$("#alertBox").text("上传失败");
}
});
}
})
} }
//用来延时显示更好的效果
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> <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.IO;
using System.Linq;
using System.Web; namespace WebApplication1
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
try
{
//从Request中取参数,注意上传的文件在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("/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)
{ throw;
}
context.Response.ContentType = "text/plain"; } public bool IsReusable
{
get
{
return false;
}
}
}
}