简体   繁体   中英

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.

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

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

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