Send and receive large file over streams in ASP.NET Web Api C#

后端 未结 1 697
你的背包
你的背包 2020-12-13 10:53

I\'m working on a project where I need to send large audio files via streams from a client to a server. I\'m using the ASP.NET Web Api to communicate between client and serv

相关标签:
1条回答
  • 2020-12-13 11:28

    if I send a large file my server gets a "outofmemoryexception"

    Well, it's reading the entire stream into memory right here:

    byte[] receivedBytes = await Request.Content.ReadAsByteArrayAsync();
    

    What you want to do is copy the stream from one location to another, without loading it all into memory at once. Something like this should work:

    [HttpPost]
    [ActionName("AddAudio")]
    public async Task<IHttpActionResult> AddAudio([FromUri]string name)
    {
      try
      {
        string file = Path.Combine(@"C:\Users\username\Desktop\UploadedFiles", fileName);
        using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write,
            FileShare.None, 4096, useAsync: true))
        {
          await Request.Context.CopyToAsync(fs);
        }
        return Ok();
      }
      catch (Exception ex)
      {
        return BadRequest("ERROR: Audio could not be saved on server.");
      }
    }
    
    0 讨论(0)
提交回复
热议问题