gpt4 book ai didi

c# - ASP.NET WebAPI : how to perform a multipart post with file upload using WebApi HttpClient

转载 作者:IT王子 更新时间:2023-10-29 03:46:23 26 4
gpt4 key购买 nike

我有一个 WebApi 服务处理来自简单表单的上传,如下所示:

    <form action="/api/workitems" enctype="multipart/form-data" method="post">
<input type="hidden" name="type" value="ExtractText" />
<input type="file" name="FileForUpload" />
<input type="submit" value="Run test" />
</form>

但是,我不知道如何使用 HttpClient API 模拟同一个帖子。 FormUrlEncodedContent 位很简单,但如何将文件内容与名称添加到帖子中?

最佳答案

经过反复试验,下面是实际有效的代码:

using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("Foo", "Bar"),
new KeyValuePair<string, string>("More", "Less"),
};

foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}

var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Foo.txt"
};
content.Add(fileContent);

var requestUri = "/api/action";
var result = client.PostAsync(requestUri, content).Result;
}
}

关于c# - ASP.NET WebAPI : how to perform a multipart post with file upload using WebApi HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10339877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com