Search code examples
c#.nethttpclientmultipartform-datawebclient

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.


Solution

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