如何在不使用系统内存的情况下往返于dotnet核心发送大文件

时间:2019-05-15 15:57:02

标签: c# .net asp.net-core .net-core

我正在尝试从dotnet核心前端将大文件上传到api。

我尝试在此处https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2使用Microsoft的代码,但他们使用的是角度代码,我想从.net核心httpclient中进行此操作。

我可以使用它,但是上载会耗尽系统的内存,并且不会释放它。我可以预期文件大小会超过GB

我的代码如下所示。

我有一个看起来像这样的http客户端

public async Task<UploadModel> UploadFileAsync(Stream fileStream, string param1, string param2)
        {
            var uri = new Uri("upload", UriKind.Relative);

            try
            {               

                var ch = GetClaimsMessageProcessor();

                var fileStreamContent = new StreamContent(fileStream);

                using (var mfdContent =
             new MultipartFormDataContent("Upload----" + DateTime.Now.ToString()))
                {
                    mfdContent.Add(fileStreamContent);

                    var response = await _restClient.PostAsync(uri, mfdContent, callbacks: new Action<HttpRequestMessage>[] { ch.AddClaims,
                       (x) => {
                           x.Headers.Add("param1",param1);
                           x.Headers.Add("param2",param1);
                        } });

                    var content = await response.Content.ReadAsStringAsync();

                    if (!response.IsSuccessStatusCode)
                    {
                        // log and throw exception etc
                    }

                    return JsonConvert.DeserializeObject<UploadModel>(content);
                }
            }
            catch (Exception e)
            {
                // log etc
            }
        }

我的api看起来像这样

[HttpPost("upload")]
        [Filters.DisableFormValueModelBinding]
        public async Task<IActionResult> Upload()
        {

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
            }

            // Get Header Parameters
            string param1, param2;

            try
            {
                param1 = Request.Headers["param1"][0];
                param2 = Request.Headers["param2"][0];
            }
            catch (Exception e)
            {
                // log and throw exception
            }          

            var filePath = GetFilePath();

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            var targetFilePath = Path.Combine(filePath , GetFileName());


            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();
            while (section != null)
            {
                using (var targetStream = System.IO.File.Create(targetFilePath))
                {
                    await section.Body.CopyToAsync(targetStream);
                }

                section = await reader.ReadNextSectionAsync();
            }

            // Validate 

            // Do stuff with uploaded file
            var model = new UploadedModel
            {
                //some properties
            };

            return Ok(model);
        }

我注意到只读了一节。我认为应该有多个?

0 个答案:

没有答案