jq +.net 切片上傳檔案
切片上傳檔案
js:
var method = "UploadDBMutipart";
var uploadresult = UploadDBMutipart(method);
/*分段上傳
*@method UploadDBMutipart BYTES_PER_CHUNK 分段大小 ,totalSlices段數,
*
*/
const BYTES_PER_CHUNK = 1024 * 1024 * 10; // 每個檔案切片大小定為10MB .
var slices;
var totalSlices; //傳送請求
function UploadDBMutipart(method) {
var blob = document.getElementById('filebox_file_id_2').files[0];//filebox_file_id_2 這個值要注意後期會不會發生變化,它是easyUI自己生成的一個ID
if (blob.size > 1024 * 1024 * 1024) {
alert("當前檔案超出最大上傳大小1GB,請使用上傳工具上傳!");
return "outsize";
}
var start = 0;
var end;
var index = 0; // 計算檔案切片總數
var result;
slices = Math.ceil(blob.size / BYTES_PER_CHUNK);
totalSlices = slices;
while (start < blob.size) {
console.info("index-" + index);
end = start + BYTES_PER_CHUNK;
if (end > blob.size) {
end = blob.size;
}
if (blob == null || blob == undefined || blob == "undefined") { console.log("blob is null"); return; }
uploadFile(blob, index, start, end, method, function (xhr) {
if (xhr.readyState == 4 && xhr.status == 200) {
result = xhr.responseText;
if (result) {
console.debug('finish');//告訴使用者上傳OK
}
else {
console.debug('slices-' + slices);
}
slices--; //分片逐漸減少,一步減一個
}
else if (xhr.status == 500) {
console.error('UploadDBMutipart error 500');
}
else {
}
});
start = end;
index++;
if (slices == 0) {
//alert('upload was finished!!!');
}
}
return result;
}
//上傳檔案
function uploadFile(blob, index, start, end, method, callbackfunc) {
var xhr;
var fd;
var chunk;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
callbackfunc(xhr);
};
chunk = blob.slice(start, end);//切割檔案
//構造form資料
fd = new FormData();
fd.append("Filedata", chunk);
fd.append("method", method);
fd.append("Filelength", blob.size);
fd.append("name", blob.name);
fd.append("start", start);
fd.append("index", index);
xhr.open("POST", "../../CommonCla/FileUploadDB.ashx", false); //設定二進位制文邊界件頭
xhr.setRequestHeader("X_Requested_With", location.href.split("/")[3].replace(/[^a-z]+/g, '$'));
xhr.send(fd);
}
後臺:
/// <summary>
/// 上傳檔案
/// </summary>
/// <param name="context"></param>
private void UploadDBMutipart(HttpContext context)
{
HttpPostedFile file = context.Request.Files["Filedata"];
string Filelength = context.Request["Filelength"];//Filelength
string name = context.Request["name"];//filename
string start = context.Request["start"];//start offset
string index = context.Request["index"];//part num
string result = string.Empty;
string fileType = Path.GetExtension(name).ToLower();
if (!fileType.Equals(".db"))
{
msg = "上傳錯誤:檔案格式錯誤,請選擇.db資料包";
LogAPI.Debug(xzqdm + msg + ":" + file.ContentType + ",字尾名:" + fileType);
MsgShow(false, msg);
Result = false;
}
FileSaveUrl = context.Server.MapPath(DBPath + "/" + name);//TODO檢查是否覆蓋了其他檔案,路徑。。。
if (file == null)
throw new Exception("Data不能為空");
try
{
lock (MD5LOCK)
{
//初始化data資料,兩種資料傳遞方式
byte[] uploadData = new byte[file.ContentLength];
if (file != null)
{
Stream stream = file.InputStream;
stream.Read(uploadData, 0, file.ContentLength);
stream.Seek(0, SeekOrigin.Begin);
}
string targetPath = FileSaveUrl;
string targetDirPath = Path.GetDirectoryName(targetPath);
if (!Directory.Exists(targetDirPath))
{
Directory.CreateDirectory(targetDirPath);
}
string tempPath = targetDirPath + "\\temp";
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
string tempFilePath = Path.Combine(tempPath, Path.GetFileName(targetPath));
int targetFileLength = 0;
int fslength = 0;
using (FileStream fs = File.OpenWrite(tempFilePath))
{
targetFileLength = (int)fs.Length;
using (BinaryWriter write = new BinaryWriter(fs))
{
long offset = Convert.ToInt64(start);
write.Seek((int)offset, SeekOrigin.Begin);
write.Write(uploadData);
fslength = (int)fs.Length;
}
}
if (fslength.ToString() == Filelength)
{
HttpCookie fileCookie = new HttpCookie("file");
fileCookie.Values["fileName"] = HttpUtility.UrlEncode(file.FileName);
fileCookie.Values["fileSavePath"] = HttpUtility.UrlEncode(FileSaveUrl);
fileCookie.Values["fileContentLength"] = HttpUtility.UrlEncode(file.ContentLength.ToString());
fileCookie.Expires = DateTime.Now.AddDays(1);
context.Response.AppendCookie(fileCookie);
//TODO md5
FileOperate.Move(tempFilePath, targetDirPath);//移動到正式目錄
FileOperate.DeleteDirectory(tempPath);//刪除臨時GUID目錄
result = FileSaveUrl;
}
else
{
result = null;/*"has uploaded " + (Convert.ToInt32(index) + 1) + " part "*/
}
}
}
catch (Exception ex)
{
result = null;
LogAPI.Error(ex);
}
context.Response.Write(result);
}