using System; using System.IO; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace FileUpload.Controllers { [ApiController] public class UploadController : ControllerBase { private const int ChunkSize = 1024 * 1024 * 1; // 每个分片的大小,这里设为1MB private const string UploadPath = "uploads"; // 文件上传目录 private static string _filePath; // 完整的文件路径 [HttpPost("/upload/start")] public ActionResult StartUpload(IFormFile file) { if (file == null || file.Length <= 0) { return BadRequest("请选择要上传的文件"); } // 生成文件名 string fileName = file.FileName; string fileExt = Path.GetExtension(fileName); string newFileName = Guid.NewGuid().ToString("N") + fileExt; // 生成文件存储目录 string dirPath = Path.Combine(Directory.GetCurrentDirectory(), UploadPath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } // 生成文件路径 _filePath = Path.Combine(dirPath, newFileName); // 返回上传开始的响应 return Ok(new { FileName = newFileName, ChunkSize, }); } [HttpPost("/upload/append")] public ActionResult AppendUpload(string fileName, int chunkIndex, int chunks, IFormFile chunk) { byte[] buffer = new byte[ChunkSize]; int bytesRead = 0; int start = chunkIndex * ChunkSize; // 分片开始位置 int end = Math.Min(start + ChunkSize, (int)chunk.Length); // 分片结束位置 using (Stream stream = chunk.OpenReadStream()) { using (FileStream fileStream = new FileStream(_filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) { fileStream.Position = start; while ((bytesRead = stream.Read(buffer, 0, Math.Min(buffer.Length, end - start))) > 0) { fileStream.Write(buffer, 0, bytesRead); start += bytesRead; } fileStream.Flush(true); } } // 检查是否所有分片都上传成功 int[] uploadedChunks = Directory.GetFiles(Path.GetDirectoryName(_filePath), $"{Path.GetFileName(_filePath)}_*").Select(filepath => int.Parse(filepath.Split('_')[1])).ToArray(); if (uploadedChunks.Length == chunks) { // 合并分片 using (FileStream fileStream = new FileStream(_filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) { foreach (int index in uploadedChunks.OrderBy(i => i)) { string chunkPath = $"{_filePath}_{index}"; using (FileStream chunkStream = new FileStream(chunkPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { chunkStream.CopyTo(fileStream); } System.IO.File.Delete(chunkPath); // 删除已合并的分片 } fileStream.Flush(true); } } return Ok(); } } }
时间: 2023-06-05 19:07:53 浏览: 189
System.Data.SQLite x86.rar
这段代码是一个用于文件上传的 ASP.NET Core 控制器,包含两个 POST 方法:StartUpload 和 AppendUpload。StartUpload 方法接收一个 IFormFile 对象,用于启动文件上传并返回文件名和每个分片的大小。AppendUpload 方法接收文件名、当前分片索引、总分片数和当前分片数据,将当前分片写入文件并检查是否所有分片都上传成功,最后返回 Ok 结果。
阅读全文