Home > database >  Send more than 1 file over HttpClient Post request c#
Send more than 1 file over HttpClient Post request c#

Time:01-02

I'm currently working with an API and I have to send files thanks to http post protocol.

With postman, everithing works fine and I can send an array of files that can contains more than 1 file:

enter image description here

For that, I'm using HttpClient in my c# application, but I only can send one file. Moreover, my body must contains form-data body so I created a MultipartFormDataContent object for send my file.

public async Task<SubmitIdentityResults> SubmitIdentity(Guid companyId, DocumentTypes docType, SubmitIdentityParameters submitIdentityParameters)
{
    try
    {
        var accesstoken = await _authTokenFromClientID.GetAccessToken();
        var client = _httpClientFactory.CreateClient("MyClient");
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accesstoken);

        MultipartFormDataContent form = new MultipartFormDataContent();
        form.Add(new StreamContent(submitIdentityParameters.File!), "Files", submitIdentityParameters.FileName!);

        var response = await client.PostAsync($"api/Document/{docType.ToString()}", form);

        if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
        {
            return default(SubmitIdentityResults)!;
        }
        
        return await response.Content.ReadFromJsonAsync<SubmitIdentityResults>() ?? default(SubmitIdentityResults)!;

    }
    catch (Exception)
    {
        throw;
    }
}

There is a way to develop the same bahaviour in c# with httpclient and mulitipartformdata ?

CodePudding user response:

I think you should pass an array SubmitIdentityParameters[] submitIdentityParameters and do like this.

foreach (var file in submitIdentityParameters)
{
    form.Add(new StreamContent(file.File!), "Files", file.FileName!);
}
  • Related