如何使用HttpClient发布表单数据IFormFile?

时间:2019-03-29 08:01:57

标签: c# http post asp.net-core multipartform-data

我有后端端点Task<ActionResult> Post(IFormFile csvFile),需要从HttpClient调用此端点。目前,我正在获取Unsupported media type error。 这是我的代码:

var filePath = Path.Combine("IntegrationTests", "file.csv");
var gg = File.ReadAllBytes(filePath);
var byteArrayContent = new ByteArrayContent(gg);
var postResponse = await _client.PostAsync("offers", new MultipartFormDataContent
{
    {byteArrayContent }
});

5 个答案:

答案 0 :(得分:3)

您需要在MultipartFormDataContent集合中指定匹配操作参数名称(csvFile)的参数名称和随机文件名

var multipartContent = new MultipartFormDataContent();
multipartContent.Add(byteArrayContent, "csvFile", "filename");
var postResponse = await _client.PostAsync("offers", multipartContent);

或同等

var postResponse = await _client.PostAsync("offers", new MultipartFormDataContent {
    { byteArrayContent, "csvFile", "filename" }
});

答案 1 :(得分:2)

使用以下代码段:

const string url = "https://localhost:5001/api/Upload";
const string filePath = @"C:\Path\To\File.png";

using (var httpClient = new HttpClient())
{
    using (var form = new MultipartFormDataContent())
    {
        using (var fs = File.OpenRead(filePath))
        {
            using (var streamContent = new StreamContent(fs))
            {
                using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
                {
                    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

                    // "file" parameter name should be the same as the server side input parameter name
                    form.Add(fileContent, "file", Path.GetFileName(filePath));
                    HttpResponseMessage response = await httpClient.PostAsync(url, form);
                }
            }
        }
    }
}

答案 2 :(得分:1)

这对我来说是通用的

public static Task<HttpResponseMessage> PostFormDataAsync<T>(this HttpClient httpClient, string url, string token, T data)
    {
        var content = new MultipartFormDataContent();

        foreach (var prop in data.GetType().GetProperties())
        {
            var value = prop.GetValue(data);
            if (value is FormFile)
            {
                var file = value as FormFile;
                content.Add(new StreamContent(file.OpenReadStream()), prop.Name, file.FileName);
                content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = prop.Name, FileName = file.FileName };
            }
            else
            {
                content.Add(new StringContent(JsonConvert.SerializeObject(value)), prop.Name);
            }
        }

        if (!string.IsNullOrWhiteSpace(token))
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        return httpClient.PostAsync(url, content);
    }

答案 3 :(得分:0)

通过使用以下代码解决:

const string fileName = "csvFile.csv";
        var filePath = Path.Combine("IntegrationTests", fileName);
        var bytes = File.ReadAllBytes(filePath);
        var form = new MultipartFormDataContent();
        var content = new StreamContent(new MemoryStream(bytes));
        form.Add(content, "csvFile");
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "csvFile",
            FileName = fileName
        };
        content.Headers.Remove("Content-Type");
        content.Headers.Add("Content-Type", "application/octet-stream; boundary=----WebKitFormBoundaryMRxYYlVt8KWT8TU3");
        form.Add(content);

        //Act
        var postResponse = await _sellerClient.PostAsync("items/upload", form);

答案 4 :(得分:0)

将附件作为 MultipartFormDataContent

发布
var type = typeof(Startup);
            var stream = type.Assembly.GetManifestResourceStream(type, "Resources.New.docx");
        var fileContent = new StreamContent(stream);
var data = new MultipartFormDataContent
            {
                { fileContent, "file", "New.docx" }
            };

        var response = await _client.PostAsync("upload", multipartContent);

来源:https://medium.com/@woeterman_94/c-webapi-upload-files-to-a-controller-e5ccf288b0ca