使用C# HttpClient进行文件POST而不使用multipart/form-data

3
我正在尝试与不支持multipart/form-data上传文件的API交互。 我已经能够通过旧版WebClient使其工作,但由于它已被弃用,我想利用更新的HttpClient。 使用WebClient与此端点配合使用的代码如下:
            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();
            }

我还没有找到一种使用 HttpClient 实现等效上传的方法,因为它似乎总是使用 multipart.


1
如果文件内容不应该作为multipart/form-data传输,那么应该以什么方式进行传输? - gunr2171
2个回答

2

我觉得它可能看起来像这样

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

1
使用只有 HttpClient 的 PostAsync 方法和 ByteArrayContent 会有什么问题呢?
byte[] fileData = ...;

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

myHttpClient.PostAsync(uploadURI, payload);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接