How to post and receive a file with web api

前端 未结 1 1265
情深已故
情深已故 2021-01-29 03:33

I have a Api Post method that I want to be able to accept any file type and that looks like this:

[HttpPost]
    public async Task Post(         


        
1条回答
  •  粉色の甜心
    2021-01-29 04:13

    The MultipartFormDataContent from the System.Net.Http namespace will allow you to post multipart form data.

    private async Task PostAttachment(byte[] data, Uri url, string contentType)
    {
      HttpContent content = new ByteArrayContent(data);
    
      content.Headers.ContentType = new MediaTypeHeaderValue(contentType); 
    
      using (var form = new MultipartFormDataContent())
      {
        form.Add(content);
    
        using(var client = new HttpClient())
        {
          var response = await client.PostAsync(url, form);
          return await response.Content.ReadAsStringAsync();
        }
      }
    }
    

    0 讨论(0)
提交回复
热议问题