简体   繁体   中英

Pass Files in C# HttpClient Post request

I am writing code in C# to consume POST API that accepts form-body with the following parameters.

Files[Array] (User can send multiple files in request)

TemplateId[Int]

Also, I need to pass the bearer AuthToken as a header in the HTTP client Post Request.

I need some help writing the HTTP request with the above form data.

using (var client = new HttpClient())
{
   HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, $" {_apiBaseUri}/{route}");

   requestMessage.Headers.Authorization = new AuthenticationHeaderValue($"Bearer {authToken}");
   var pdfFiles = Directory.GetFiles($"C:\\files", "*.pdf");
   foreach (var filename in pdfFiles)
   {
      // create array[] of each File and add them to the form data request
   }
   // Add TemplateId in the form data request
} 

postman request 在此处输入图像描述

swagger request 在此处输入图像描述

you can add files with 'MultipartFormDataContent'.

private static async Task UploadSampleFile()
{
    var client = new HttpClient
    {
        BaseAddress = new("https://localhost:5001")
    };

    await using var stream = System.IO.File.OpenRead("./Test.txt");
    using var request = new HttpRequestMessage(HttpMethod.Post, "file");
    using var content = new MultipartFormDataContent
    {
        { new StreamContent(stream), "file", "Test.txt" }
    };

    request.Content = content;

    await client.SendAsync(request);
}

for more: https://brokul.dev/sending-files-and-additional-data-using-httpclient-in.net-core

The Below Code change worked for me,

using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), _apiBaseUri))
    {
        request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {authToken}");

        var pdfFiles = Directory.GetFiles($"C:\\test", "*.pdf");
        var multipartContent = new MultipartFormDataContent();
        multipartContent.Add(new StringContent("100"), "templateId");
        foreach (var filename in pdfFiles)
        {
            multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(filename)), "files", Path.GetFileName(filename));
        }
        request.Content = multipartContent;

        var response = await httpClient.SendAsync(request);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM