Html 5は微信の制限を突破して大きいファイルの分割のアップロードを実現します
3962 ワード
フロントエンドコード
var page = {
init: function () {
$("#subUpload").click($.proxy(this.upload, this));
},
upload: function () {
var file = $("#fileUpload")[0].files[0], //
name = file.name, //
size = file.size, //
succeed = 0;
var shardSize = 290 * 1024, // 290kb , 1MB=1 * 1024 * 1024
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: "../Upload/SaveFile2",
type: "POST",
data: form,
async: true, //
processData: false, // , jquery form
contentType: false, // , false Content-Type
success: function () {
++succeed;
$("#output").text(succeed + " / " + shardCount);
}
});
}
}
};
$(function () {
page.init();
});
またC#版バックグラウンドコード public ActionResult SaveFile2()
{
string name = Request["name"];
int total = Convert.ToInt32(Request["total"]);
int index = Convert.ToInt32(Request["index"]);
var data = Request.Files["data"];
string dir = Server.MapPath("/UploadFile/Imgs/");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string file = Path.Combine(dir, name + "_" + index);
data.SaveAs(file);
string[] files = Directory.GetFiles(dir);
bool isMerge = true;
for (int i = 1; i <= total; ++i)
{
string part = Path.Combine(dir, name + "_" + i);
if (!files.Contains(part))
{
isMerge = false;
}
}
if (isMerge)
{
file = Path.Combine(dir, name);
var fs = new FileStream(file, FileMode.Create);
try {
for (int i = 1; i <= total; ++i)
{
string part = Path.Combine(dir, name + "_" + i);
var bytes = System.IO.File.ReadAllBytes(part);
fs.Write(bytes, 0, bytes.Length);
bytes = null;
System.IO.File.Delete(part);
}
}
finally
{
fs.Close();
}
}
// ,
return Json(new { Error = 0 });
}