Home > Software engineering >  Using C# HttpClient to POST File without multipart/form-data
Using C# HttpClient to POST File without multipart/form-data

Time:05-14

I'm trying to interact with a API that doesn't support multipart/form-data for uploading a file.

I've been able to get this to work with the older WebClient but since it's being deprecated I wanted to utilize the newer HttpClient.

The code I have for WebClient that works with this end point looks like this:

            using (WebClient client = new WebClient())
            {
                byte[] file = File.ReadAllBytes(filePath);

                client.Headers.Add("Authorization", apiKey);
                client.Headers.Add("Content-Type", "application/pdf");
                byte[] rawResponse = client.UploadData(uploadURI.ToString(), file);
                string response = System.Text.Encoding.ASCII.GetString(rawResponse);

                JsonDocument doc = JsonDocument.Parse(response);
                return doc.RootElement.GetProperty("documentId").ToString();
            }

I've not found a way to get an equivalent upload to work with HttpClient since it seems to always use multipart.

CodePudding user response:

What speaks against using simply HttpClient's PostAsync method in conjunction with ByteArrayContent?

byte[] fileData = ...;

var payload = new ByteArrayContent(fileData);
payload.Headers.Add("Content-Type", "application/pdf");

myHttpClient.PostAsync(uploadURI, payload);

CodePudding user response:

I think it would look something like this

using var client = new HttpClient();

var file = File.ReadAllBytes(filePath);

var content = new ByteArrayContent(file);
content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

var result = client.PostAsync(uploadURI.ToString(), content).Result;
result.EnsureSuccessStatusCode();

var response = await result.Content.ReadAsStringAsync();
var doc = JsonDocument.Parse(response);

return doc.RootElement.GetProperty("documentId").ToString();
  • Related