如何使用c#将MultipartFormDataContent数组发送到api

时间:2018-05-04 04:14:14

标签: c#

我想将一个multipartformDataContent数组发送到api。

MultipartFormDataContent[] content = new MultipartFormDataContent[Array.Length];

            for (int i = 0; i < Array.Length; i++)
            {
                foreach (var para in Array[i])
                {
                    if (para.Key == "file")
                    {
                        FileParameter fileToUpload = (FileParameter)para.Value;
                        var stream = new MemoryStream(fileToUpload.File);
                        content[i].Add(new StreamContent(stream), para.Key, fileToUpload.FileName);
                    }
                    else
                    {
                        String String = para.Value.ToString();
                        content[i].Add(new StringContent(String), para.Key);
                    }
                }

            }

我想将这个multipartformdataContent数组发布到api。有可能吗?

1 个答案:

答案 0 :(得分:0)

以下是将FileContent与其他数据合并到MultipartFormDataContent中所需的内容:

using (var memoryStream = new MemoryStream())
{
    // Copy your file into memoryStream
    memoryStream.Position = 0;
    var fileContent = new ByteArrayContent(memoryStream.ToArray());
    var multiContent = new MultipartFormDataContent {{fileContent, "File", "Blah.pdf"}};
    foreach (var pair in nameValues)
    {
        multiContent.Add(new StringContent(pair.Value), pair.Key);
    }

    return await httpClient.PostAsync(requestUri, multiContent);
}