如何在 C# Endpoint WEB API 的服务器端实现对每个文件的下载进度的跟踪?

How to implement tracking the download progress of each file on the server side of the C# Endpoint WEB Api?

提问人:komilffo_d 提问时间:10/27/2023 最后编辑:komilffo_d 更新时间:10/27/2023 访问量:37

问:

将接收表单文件的集合作为输入。不要过早地将文件上传到缓冲区,而是要读取、跟踪进度并保存到文件系统。

我尝试使用 Request.ReadFromAsync - 失败了......我接受 Request.Body - 就像一条流 - 同样的故事

    [HttpPost(Name = "UploadFile", Order = 1)]
    [Authorize]
    [RequestSizeLimit(1_024_000_000)]
    public async Task<ActionResult<List<FileDto>>?> UploadFile([FromForm]IFormFileCollection filesUpload)
    {
        Request.EnableBuffering();

        var directory = Tools.CreateRelativeDirectory("Files");
        var filesDto = new List<FileDto>();
        var accountDb = await _accountRepository.CheckAuthorization(Request);

        foreach (var fileUpload in filesUpload)
        {

            ControllerContext.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

            using (FileStream stream = new FileStream(Path.Combine(directory.FullName, fileUpload.FileName), FileMode.Create, FileAccess.Write))
            {
                using (ProgressStream progressStream = new ProgressStream(fileUpload.OpenReadStream()))
                {
                    progressStream.UpdateProgress += UpdateProgress!;
                    progressStream.CopyTo(stream);
                    var created = await _fileRepository.Create(new FileDb
                    {
                        FileName = Path.Combine(directory.Name, fileUpload.FileName),
                        FileType = MimeMapping.MimeUtility.GetMimeMapping(fileUpload.FileName),
                        AccountId = accountDb!.Id,
                        Shared = Request.HttpContext.User.FindFirst(ClaimsIdentity.DefaultRoleClaimType).Value == EnumReflection.GetDescription<Role>(Role.ADMIN) ? true : false
                    });

                    filesDto.Add(new FileDto(created.Id, created.FileName, created.FileType));
                }


            }
        }

        return Created(Tools.GetUrl(Request), filesDto);


    }
C# .NET 文件 上传 webapi

评论

0赞 komilffo_d 10/27/2023
是的,我明白了......我把它们写成一个例子,仅此而已
0赞 hakim00 10/27/2023
您应该考虑将其作为代码而不是屏幕截图包含在内。
0赞 komilffo_d 10/27/2023
在问题文本中添加了列表

答: 暂无答案