1. 程式人生 > >C#為例,分塊上傳檔案

C#為例,分塊上傳檔案

前臺:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="../Scripts/jquery-1.8.2.js"></script>
</head>
<body>
<input type="file" id="file" />
<button id="upload">上傳</button>
<span id="output">等待中</span>
</body>
<script>
var page = {
init: function () {
$("#upload").click($.proxy(this.upload, this));
},

upload: function () {
var file = $("#file")[0].files[0], //檔案物件
name = file.name, //檔名
size = file.size, //總大小
succeed = 0;

var shardSize = 4 * 1024 * 1024, //以4MB為一個分片
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: "../Test/Upload",
type: "POST",
data: form,
async: true, //非同步
processData: false, //jquery不要對form進行處理
contentType: false, //指定為false才能形成正確的Content-Type
success: function () {
//成功後的事件
succeed++;
if (succeed == shardCount)
{
Merge();
}
}
});
}
}


};

function Merge() {
$.ajax({
url: "../Test/Merge",
type: "get",
success: function () {

}
});
}

$(function () {
page.init(); //初始化
});

</script>
</html>

後臺:

[HttpPost]
public ActionResult Upload()
{
string fileName = Request["name"];
int index = Convert.ToInt32(Request["index"]);//當前分塊序號
var folder = "myTest";
var dir = Server.MapPath("~/Images");//檔案上傳目錄
dir = Path.Combine(dir, folder);//臨時儲存分塊的目錄
if (!System.IO.Directory.Exists(dir))
System.IO.Directory.CreateDirectory(dir);
string filePath = Path.Combine(dir, index.ToString());
var data = Request.Files["data"];//表單中取得分塊檔案
data.SaveAs(filePath);//儲存
return Json(new { erron = 0 });
}


public ActionResult Merge()
{
var folder = "myTest";
var uploadDir = Server.MapPath("~/Images");//Upload 資料夾
var dir = Path.Combine(uploadDir, folder);//臨時資料夾
var fileName = "MyTest.jpg";//檔名
var files = System.IO.Directory.GetFiles(dir);//獲得下面的所有檔案
var finalPath = Path.Combine(uploadDir, fileName);//最終的檔名(demo中儲存的是它上傳時候的檔名,實際操作肯定不能這樣)
var fs = new FileStream(finalPath, FileMode.Create);
foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保證從0-N Write
{
var bytes = System.IO.File.ReadAllBytes(part);
fs.Write(bytes, 0, bytes.Length);
bytes = null;
System.IO.File.Delete(part);//刪除分塊
}
fs.Close();
System.IO.Directory.Delete(dir);//刪除資料夾
return Json(new { error = 0 });//隨便返回個值,實際中根據需要返回
}