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);

}

猜你喜欢

转载自blog.csdn.net/weixin_44296167/article/details/85279525
jq