该项目是基于.NET Core 和 Jquery实现的文件分片上传,没有经过测试,因为博主没有那么大的文件去测试,目前上传2G左右的文件是没有问题的。
为什么要用到Redis,文章后面再说,先留个悬念。

Microsoft.Extensions.Caching.StackExchangeRedis
Zack.ASPNETCore 杨中科封装的操作Redis包
在实现代码的时候,我们需要了解文件为什么要分片上传,我直接上传不行吗。大家在使用b站、快手等网站的视频上传的时候,可以发现文件中断的话,之前已经上传了的文件再次上传会很快。这就是分片上传的好处,如果发发生中断,我只要上传中断之后没有上传完成的文件即可,当一个大文件上传的时候,用户可能会断网,或者因为总总原因导致上传失败,但是几个G的文件,难不成又重新上传吗,那当然不行。
具体来说,分片上传文件的原理如下:
总的来说,分片上传文件的原理就是将一个大文件分成若干个小文件块,分别上传到服务器,最后再将这些小文件块合并成一个完整的文件。
在了解原理之后开始实现代码。
首先在Program.cs配置文件中注册reidis服务
builder.Services.AddScoped<IDistributedCacheHelper, DistributedCacheHelper>();
//注册redis服务
builder.Services.AddStackExchangeRedisCache(options =>
{
string connStr = builder.Configuration.GetSection("Redis").Value;
string password = builder.Configuration.GetSection("RedisPassword").Value;
//redis服务器地址
options.Configuration = $"{connStr},password={password}";
});
在appsettings.json中配置redis相关信息
"Redis": "redis地址",
"RedisPassword": "密码"
在控制器中注入
private readonly IWebHostEnvironment _environment;
private readonly IDistributedCacheHelper _distributedCache;
public UpLoadController(IDistributedCacheHelper distributedCache, IWebHostEnvironment environment)
{
_distributedCache = distributedCache;
_environment = environment;
}
从redis中取文件名
string GetTmpChunkDir(string fileName)
{
var s = _distributedCache.GetOrCreate<string>(fileName, ( e) =>
{
//滑动过期时间
//e.SlidingExpiration = TimeSpan.FromSeconds(1800);
//return Encoding.Default.GetBytes(Guid.NewGuid().ToString("N"));
return fileName.Split('.')[0];
}, 1800);
if (s != null) return fileName.Split('.')[0]; ;
return "";
}
实现保存文件方法
/// <summary>
/// 保存文件
/// </summary>
/// <param name="file">文件</param>
/// <param name="fileName">文件名</param>
/// <param name="chunkIndex">文件块</param>
/// <param name="chunkCount">分块数</param>
/// <returns></returns>
public async Task<JsonResult> SaveFile(IFormFile file, string fileName, int chunkIndex, int chunkCount)
{
try
{
//说明为空
if (file.Length == 0)
{
return Json(new
{
success = false,
mas = "文件为空!!!"
});
}
if (chunkIndex == 0)
{
////第一次上传时,生成一个随机id,做为保存块的临时文件夹
//将文件名保存到redis中,时间是s
_distributedCache.GetOrCreate(fileName, (e) =>
{
//滑动过期时间
//e.SlidingExpiration = TimeSpan.FromSeconds(1800);
//return Encoding.Default.GetBytes(Guid.NewGuid().ToString("N"));
return fileName.Split('.')[0]; ;
}, 1800);
}
if(!Directory.Exists(GetFilePath())) Directory.CreateDirectory(GetFilePath());
var fullChunkDir = GetFilePath() + dirSeparator + GetTmpChunkDir(fileName);
if(!Directory.Exists(fullChunkDir)) Directory.CreateDirectory(fullChunkDir);
var blog = file.FileName;
var newFileName = blog + chunkIndex + Path.GetExtension(fileName);
var filePath = fullChunkDir + Path.DirectorySeparatorChar + newFileName;
//如果文件块不存在则保存,否则可以直接跳过
if (!System.IO.File.Exists(filePath))
{
//保存文件块
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
//所有块上传完成
if (chunkIndex == chunkCount - 1)
{
//也可以在这合并,在这合并就不用ajax调用CombineChunkFile合并
//CombineChunkFile(fileName);
}
var obj = new
{
success = true,
date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
newFileName,
originalFileName = fileName,
size = file.Length,
nextIndex = chunkIndex + 1,
};
return Json(obj);
}
catch (Exception ex)
{
return Json(new
{
success = false,
msg = ex.Message,
});
}
}
当然也可以放到session里面,这里就不做演示了。
这是将文件名存入到redis中,作为唯一的key值,当然这里最好采用
Encoding.Default.GetBytes(Guid.NewGuid().ToString("N"));去随机生成一个id保存,为什么我这里直接用文件名,一开始写这个是为了在学校上机课时和室友之间互相传文件,所以没有考虑那么多,根据自己的需求来。
在第一次上传文件的时候,redis会保存该文件名,如果reids中存在该文件名,那么后面分的文件块就可以直接放到该文件名下。
_distributedCache.GetOrCreate(fileName, (e) =>
{
//滑动过期时间
//e.SlidingExpiration = TimeSpan.FromSeconds(1800);
//return Encoding.Default.GetBytes(Guid.NewGuid().ToString("N"));
return fileName.Split('.')[0]; ;
}, 1800);
//目录分隔符,兼容不同系统
static readonly char dirSeparator = Path.DirectorySeparatorChar;
//获取文件的存储路径
//用于保存的文件夹
private string GetFilePath()
{
return Path.Combine(_environment.WebRootPath, "UploadFolder");
}
public async Task<JsonResult> CombineChunkFile(string fileName)
{
try
{
return await Task.Run(() =>
{
//获取文件唯一id值,这里是文件名
var tmpDir = GetTmpChunkDir(fileName);
//找到文件块存放的目录
var fullChunkDir = GetFilePath() + dirSeparator + tmpDir;
//开始时间
var beginTime = DateTime.Now;
//新的文件名
var newFileName = tmpDir + Path.GetExtension(fileName);
var destFile = GetFilePath() + dirSeparator + newFileName;
//获取临时文件夹内的所有文件块,排好序
var files = Directory.GetFiles(fullChunkDir).OrderBy(x => x.Length).ThenBy(x => x).ToList();
//将文件块合成一个文件
using (var destStream = System.IO.File.OpenWrite(destFile))
{
files.ForEach(chunk =>
{
using (var chunkStream = System.IO.File.OpenRead(chunk))
{
chunkStream.CopyTo(destStream);
}
System.IO.File.Delete(chunk);
});
Directory.Delete(fullChunkDir);
}
//结束时间
var totalTime = DateTime.Now.Subtract(beginTime).TotalSeconds;
return Json(new
{
success = true,
destFile = destFile.Replace('\\', '/'),
msg = $"合并完成 ! {totalTime} s",
});
});
}catch (Exception ex)
{
return Json(new
{
success = false,
msg = ex.Message,
});
}
finally
{
_distributedCache.Remove(fileName);
}
}
原理就是获取文件,然后切片,通过分片然后递归去请求后端保存文件的接口。


<script src="~/lib/jquery/dist/jquery.min.js"></script>
<div class="dropzone" id="dropzone">
将文件拖拽到这里上传<br>
或者<br>
<input type="file" id="file1">
<button for="file-input" id="btnfile" value="Upload" class="button">选择文件</button>
<div id="progress">
<div id="progress-bar"></div>
</div>
<div id="fName" style="font-size:16px"></div>
<div id="percent">0%</div>
</div>
<button id="btnQuxiao" class="button2" disabled>暂停上传</button>
<div id="completedChunks"></div>
稍微让页面能够看得下去
<style>
.dropzone {
border: 2px dashed #ccc;
padding: 25px;
text-align: center;
font-size: 20px;
margin-bottom: 20px;
position: relative;
}
.dropzone:hover {
border-color: #aaa;
}
#file1 {
display: none;
}
#progress {
position: absolute;
bottom: -10px;
left: 0;
width: 100%;
height: 10px;
background-color: #f5f5f5;
border-radius: 5px;
overflow: hidden;
}
#progress-bar {
height: 100%;
background-color: #4CAF50;
width: 0%;
transition: width 0.3s ease-in-out;
}
#percent {
position: absolute;
bottom: 15px;
right: 10px;
font-size: 16px;
color: #999;
}
.button{
background-color: greenyellow;
}
.button, .button2 {
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
margin-right: 10px;
}
.button2 {
background-color: grey;
}
</style>
<script>
$(function(){
var pause = false;//是否暂停
var $btnQuxiao = $("#btnQuxiao"); //暂停上传
var $file; //文件
var $completedChunks = $('#completedChunks');//上传完成块数
var $progress = $('#progress');//上传进度条
var $percent = $('#percent');//上传百分比
var MiB = 1024 * 1024;
var chunkSize = 8.56 * MiB;//xx MiB
var chunkIndex = 0;//上传到的块
var totalSize;//文件总大小
var totalSizeH;//文件总大小M
var chunkCount;//分块数
var fileName;//文件名
var dropzone = $('#dropzone'); //拖拽
var $fileInput = $('#file1'); //file元素
var $btnfile = $('#btnfile'); //选择文件按钮
//通过自己的button按钮去打开选择文件的功能
$btnfile.click(function(){
$fileInput.click();
})
dropzone.on('dragover', function () {
$(this).addClass('hover');
return false;
});
dropzone.on('dragleave', function () {
$(this).removeClass('hover');
return false;
});
dropzone.on('drop', function (e) {
setBtntrue();
e.preventDefault();
$(this).removeClass('hover');
var val = $('#btnfile').val()
if (val == 'Upload') {
$file = e.originalEvent.dataTransfer.files[0];
if ($file === undefined) {
$completedChunks.html('请选择文件 !');
return false;
}
totalSize = $file.size;
chunkCount = Math.ceil(totalSize / chunkSize * 1.0);
totalSizeH = (totalSize / MiB).toFixed(2);
fileName = $file.name;
$("#fName").html(fileName);
$('#btnfile').val("Pause")
pause = false;
chunkIndex = 0;
}
postChunk();
});
$fileInput.change(function () {
setBtntrue();
console.log("开始上传文件!")
var val = $('#btnfile').val()
if (val == 'Upload') {
$file = $fileInput[0].files[0];
if ($file === undefined) {
$completedChunks.html('请选择文件 !');
return false;
}
totalSize = $file.size;
chunkCount = Math.ceil(totalSize / chunkSize * 1.0);
totalSizeH = (totalSize / MiB).toFixed(2);
fileName = $file.name;
$("#fName").html(fileName);
$('#btnfile').val("Pause")
pause = false;
chunkIndex = 0;
}
postChunk();
})
function postChunk() {
console.log(pause)
if (pause)
return false;
var isLastChunk = chunkIndex === chunkCount - 1;
var fromSize = chunkIndex * chunkSize;
var chunk = !isLastChunk ? $file.slice(fromSize, fromSize + chunkSize) : $file.slice(fromSize, totalSize);
var fd = new FormData();
fd.append('file', chunk);
fd.append('chunkIndex', chunkIndex);
fd.append('chunkCount', chunkCount);
fd.append('fileName', fileName);
$.ajax({
url: '/UpLoad/SaveFile',
type: 'POST',
data: fd,
cache: false,
contentType: false,
processData: false,
success: function (d) {
if (!d.success) {
$completedChunks.html(d.msg);
return false;
}
chunkIndex = d.nextIndex;
//递归出口
if (isLastChunk) {
$completedChunks.html('合并 .. ');
$btnfile.val('Upload');
setBtntrue();
//合并文件
$.post('/UpLoad/CombineChunkFile', { fileName: fileName }, function (d) {
$completedChunks.html(d.msg);
$completedChunks.append('destFile: ' + d.destFile);
$btnfile.val('Upload');
setBtnfalse()
$fileInput.val('');//清除文件
$("#fName").html("");
});
}
else {
postChunk();//递归上传文件块
//$completedChunks.html(chunkIndex + '/' + chunkCount );
$completedChunks.html((chunkIndex * chunkSize / MiB).toFixed(2) + 'M/' + totalSizeH + 'M');
}
var completed = chunkIndex / chunkCount * 100;
$percent.html(completed.toFixed(2) + '%').css('margin-left', parseInt(completed / 100 * $progress.width()) + 'px');
$progress.css('background', 'linear-gradient(to right, #ff0084 ' + completed + '%, #e8c5d7 ' + completed + '%)');
},
error: function (ex) {
$completedChunks.html('ex:' + ex.responseText);
}
});
}
$btnQuxiao.click(function(){
var val = $('#btnfile').val();
if (val == 'Pause') {
$btnQuxiao.css('background-color', 'grey');
val = 'Resume';
pause = true;
} else if (val === 'Resume') {
$btnQuxiao.css('background-color', 'greenyellow');
val = 'Pause';
pause = false;
}
else {
$('#btnfile').val("-");
}
console.log(val + "" + pause)
$('#btnfile').val(val)
postChunk();
})
//设置按钮可用
function setBtntrue(){
$btnQuxiao.prop('disabled', false)
$btnQuxiao.css('background-color', 'greenyellow');
}
//设置按钮不可用
function setBtnfalse() {
$btnQuxiao.prop('disabled', true)
$btnQuxiao.css('background-color', 'grey');
}
})
</script>
var isLastChunk = chunkIndex === chunkCount - 1;
当isLastChunk 为true时,执行合并文件,这里就不会再去请求保存文件了。
分片上传文件原理很简单,根据原理去实现代码,慢慢的摸索很快就会熟练掌握,当然本文章有很多写的不好的地方可以指出来,毕竟博主还只是学生,需要不断的学习。
有问题评论,看到了会回复。
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A
我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只