大文件上传,分片 ASP.NET API

 
Double-click
Select to translate
 
 
 
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;
    });
}

 

posted @ 2023-05-12 17:14  skywss27  阅读(24)  评论(0)    收藏  举报