title: How to get image data from request body in Azure Functions v2 and convert to Stream
body: <p>I need to read image send to Azure Function v2 as Stream and then pass that Stream to method to work with image. </p>
  
  <p>I tried several approaches ie. <a href="https://stackoverflow.com/questions/54944607/how-to-retrieve-bytes-data-from-request-body-in-azure-function-app">from another question</a> or <a href="https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers" rel="nofollow noreferrer">this blog post</a> and none of them worked - every time the Stream that is passed to the method have non valid data. also if I read request Body as string it shows some crap. Final solution that I think is the most logical is posted below:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public async Task&lt;IActionResult&gt; Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
        HttpRequest req,
        ILogger log)
  {
        Product product;
        using (MemoryStream ms = new MemoryStream())
        {                
           await req.Body.CopyToAsync(ms);
           ms.Seek(0, SeekOrigin.Begin);
  
           //Then I need to pass Stream to another method that calls Azure Custom Vision endpoint
           product = await _identifyService.IdentifyProduct(ms);
        }
  }
  </code></pre>
  
  <p>Also I tried several other approaches ie.:</p>
  
  <pre class="lang-cs prettyprint-override"><code>      MemoryStream ms = new MemoryStream();
        await req.Body.CopyToAsync(ms);
        byte[] imageBytes = ms.ToArray();
        log.LogInformation(imageBytes.Length.ToString());
  
        var memoryStream = new MemoryStream(imageBytes);
        memoryStream.Seek(0, SeekOrigin.Begin);
        // Then pass memoryStream to the method.
  </code></pre>
  
  <p>or reading req.Body as string with StreamReader. None of this approaches worked.</p>
  
  <p>The request from React app done with ajax looks more or less like that (shortened it to be more readable):</p>
  
  <pre><code>
  file: File = .... //File from form
  
  const reader = new FileReader();
  reader.readAsBinaryString(file);
  var binary = reader.result;
  
  fetch(`${API_URL}/IdentifyProduct`, {
        method: 'post',
        body: binary
      }).then(function (response) {
        return response.json();
      })
  </code></pre>
  
  <p>Maybe somebody had similar problem and have solution, because I don't have any other idea how to get it work.</p>