文件分片上传

由于  传统 .NET 项目中: webconfig可以设置最大文件为2G,当上传的文件超过2G或者我们不希望更改webconfig配置时,或者为了 提高效率,并发上传,可以使用该方法。

 

 

aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="upfile22.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<input type="file" id="file6" multiple><button type="button" class="btnFile6">分片上传</button><div class="result"></div>
</form>
</body>


<script>
$(".btnFile6").click(function () {
var upload = function (file, skip) {
var formData = new FormData();//初始化一个FormData对象
var blockSize = 1000000;//每块的大小
var nextSize = Math.min((skip + 1) * blockSize, file.size);//读取到结束位置
var fileData = file.slice(skip * blockSize, nextSize);//截取 部分文件 块
formData.append("file", fileData);//将 部分文件 塞入FormData
formData.append("fileName", file.name);//保存文件名字
$.ajax({
url: "Handler.ashx",
type: "POST",
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (responseText) {
$(".result").html("已经上传了" + (skip + 1) + "块文件");
if (file.size <= nextSize) {//如果上传完成,则跳出继续上传
alert("上传完成");
return;
}
upload(file, ++skip);//递归调用
}
});
};
var file = $("#file6")[0].files[0];
upload(file, 0);
});
</script>
</html>

 

Handler:

public void ProcessRequest(HttpContext context)
{

//保存文件到指定目录
var filePath = ConfigurationManager.AppSettings["uploadPath"] +@"\" + context.Request.Form["fileName"];
//创建一个追加(FileMode.Append)方式的文件流
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
//读取文件流
BinaryReader br = new BinaryReader(context.Request.Files[0].InputStream);
//将文件留转成字节数组
byte[] bytes = br.ReadBytes((int)context.Request.Files[0].InputStream.Length);
//将字节数组追加到文件
bw.Write(bytes);
}
}
}

 

 

 

 

 

 

 

 

 

 

其他资料:将web.config 设置可以上传 2G(默认4M,<configuration>中添加)

 

<system.web>
<httpRuntime maxRequestLength="2147483647" executionTimeout="18000"/>
</system.web>
<system.webServer>
<security>
<requestFiltering >
<requestLimits maxAllowedContentLength="2147483647" ></requestLimits>
</requestFiltering>
</security>

</system.webServer>

 

posted @ 2022-01-30 14:59  越过那个限制  阅读(277)  评论(0编辑  收藏  举报