1、先談大檔上傳的策略
幾 MB 到幾十 MB 的檔案用傳統表單上傳沒問題,但檔案一大就容易遇到逾時與記憶體壓力,這時該改用分片上傳:在瀏覽器端把檔案切片逐片送到伺服器,伺服器收完再合併成完整檔案。
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>
<script>
function uploadFile() {
$("#upload").attr("disabled", "disabled");
var file = $("#file")[0].files[0],
name = file.name,
size = file.size,
succeed = 0;
var shardSize = 2 * 1024 * 1024, // 以 2MB 為一個分片
shardCount = Math.ceil(size / shardSize); // 總片數
$('.progress .progress-bar').attr('data-transitiongoal', 0).progressbar({ display_text: 'fill' });
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({
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 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" style="font-size: 12px">等待</span>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" data-transitiongoal=""></div>
</div>
</body>
</html>
幾個關鍵點:file.slice() 負責切出片段,FormData 承載整包資料,而 processData: false 與 contentType: false 這兩個設定少了任何一個,boundary 就會出錯,後端也就收不到檔案。
3、後端一般處理程序
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace Html5UploadTest {
public class Upload : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/plain";
try {
// 從 Request 取參數,注意上傳的檔案在 Request.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);
// 如果已是最後一片,進行合併
if (index == total) {
file = Path.Combine(dir, name);
using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate)) {
for (int i = 1; i <= total; ++i) {
string part = Path.Combine(dir, name + "_" + i);
System.IO.File.Delete(part);
fs.Close();
}
}
}
} catch (Exception) {
throw;
}
}
public bool IsReusable { get { return false; } }
}
}
4、還缺什麼
上面是骨幹,真正上 production 還需要補上幾件事:異常處理與失敗重試、斷點續傳(記錄已上傳的片號,重新整理後能接著傳)、檔案名校驗避免路徑穿越攻擊,以及暫存區的定期清理。另外,合併時若多個分片同時寫入同一檔案,需要控制並發以免鎖衝突——比較穩定的做法是每片各自落地,最後再依序串接。
進度條這邊,用 bootstrap-progressbar 只要更新 data-transitiongoal 就能驅動動畫,接得很乾淨;而它的百分比也應該來自真實的成功片數,而不是計時器累加,這樣使用者看到的數字才有意義。