SoFunction
Updated on 2025-03-06

Implementation of C# HttpClient Post parameters to upload files simultaneously

HttpClient Post parameters upload files simultaneously

The demo is as follows

using (var client = new HttpClient())
{
    using (var multipartFormDataContent = new MultipartFormDataContent())
    {
        var values = new[]
        {
            new KeyValuePair<string, string>("c", "3"),
            new KeyValuePair<string, string>("c", "2"),
            new KeyValuePair<string, string>("d", "2")
             //other values
        };
 
        foreach (var keyValuePair in values)
        {
            (new StringContent(),
                ("\"{0}\"", ));
        }
 
        (new ByteArrayContent((@"D:\")),
            "\"pic\"",
            "\"\"");
 
        var requestUri = "http://localhost:8080";
        var html = (requestUri, multipartFormDataContent).().Result;
    }
}

HttpClient uploads files to the server (multipart/form-data)

string reqUrl = (typeof(Wfm_SimReport).Name, "save");
using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }))//If you want to manually set cookies, you must set UseCookies = false{
                               
    string boundary = ("----WebKitFormBoundary{0}",("x"));
    MultipartFormDataContent content = new MultipartFormDataContent(boundary);
 
    #region Set request parameters     = ("multipart/form-data");
    ("Cookie", );
    ("client", "true");
 
    #endregion
    if ((fullPath) &amp;&amp; !(fullPath))
    {
        return false;
    }
 
    string fileName = (fullPath);
 
    #region Stream Request    FileStream fStream = (fullPath, , );
    (new StreamContent(fStream, (int)), "file", fileName);
                
    #endregion
    (new StringContent((entity)), "dtoStr");
    var result = (reqUrl, content).Result;
 
    try
    {
        if ()
        {
            string rslt = ().Result;
            (rslt);
            return true;
        }
    }
    catch (Exception ex)
    {
        (("Get server return result error:information:{0},Stack:{1}",,));
    }
    finally
    {
        //Close the file stream        ();
        ();
    }                
 }

The above is personal experience. I hope you can give you a reference and I hope you can support me more.