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

后端 未结 3 2140
我寻月下人不归
我寻月下人不归 2020-11-27 10:47

I have a WebApi service handling an upload from a simple form, like this one:

    
3条回答
  •  醉梦人生
    2020-11-27 11:15

    After much trial and error, here's code that actually works:

    using (var client = new HttpClient())
    {
        using (var content = new MultipartFormDataContent())
        {
            var values = new[]
            {
                new KeyValuePair("Foo", "Bar"),
                new KeyValuePair("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;
        }
    }
    

提交回复
热议问题