大文件上传,分片 ASP.NET API
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using System.IO;
using System.Threading.Tasks;
namespace LargeFileUploadApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class UploadController : ControllerBase
{
private readonly IHostEnvironment _environment;
public UploadController(IHostEnvironment environment)
{
_environment = environment;
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file, int chunkNumber, int totalChunks)
{
if (file == null || file.Length == 0)
{
return BadRequest("Empty file");
}
// 初始化上传目录
var uploadPath = Path.Combine(_environment.ContentRootPath, "uploads");
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// 将当前块写入文件
var chunkPath = Path.Combine(uploadPath, $"{file.FileName}.part{chunkNumber}");
using (var fileStream = new FileStream(chunkPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
// 如果所有块都已上传,合并它们
if (chunkNumber == totalChunks)
{
var finalFilePath = Path.Combine(uploadPath, file.FileName);
using (var finalFileStream = new FileStream(finalFilePath, FileMode.Create))
{
for (var i = 1; i <= totalChunks; i++)
{
var currentChunkPath = Path.Combine(uploadPath, $"{file.FileName}.part{i}");
using (var currentChunkStream = new FileStream(currentChunkPath, FileMode.Open))
{
await currentChunkStream.CopyToAsync(finalFileStream);
}
System.IO.File.Delete(currentChunkPath);
}
}
}
return Ok();
}
}
}
取消大小限制
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.Configure<FormOptions>(options => { options.MultipartBodyLengthLimit = long.MaxValue; options.MultipartBoundaryLengthLimit = int.MaxValue; }); }
I'm fine, it's ok

浙公网安备 33010602011771号