stonedonkey
stonedonkey

Reputation: 743

Using C# HttpClient to POST File without multipart/form-data

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.

Upvotes: 3

Views: 3394

Answers (2)

GuyVdN
GuyVdN

Reputation: 692

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 = await client.PostAsync(uploadURI.ToString(), content);
result.EnsureSuccessStatusCode();

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

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

Upvotes: 2

Occam
Occam

Reputation: 11

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);

Upvotes: 1

Related Questions