Search code examples
c#.nethttppostmanmultipartform-data

Post request body with file and text


In the Windows application, I have to upload the text file to the server, for that I am using the post APIs where I have to pass the file parameter and text parameter.

I have tried the MultipartFormDataContent for doing the same but somehow file upload is happening, and the params are not through the request body.

Attaching the postman request body: PostMan request Body

Code I have tried using MultipartFormDataContent:

RequestJson requestJson  = new RequestJson ();
requestJson.uploadFile = FilePath;  // string Path of file
requestJson.userName= "Nation";
requestJson.email = "Nation@xyz.com";

HttpContent postData = new StringContent(JsonConvert.SerializeObject(requestJson ), Encoding.Default, "application/octet-stream");
var content = new MultipartFormDataContent();
content.Add(postData, "upload", "file3.txt");

Task<HttpResponseMessage> message = client.PostAsync(ServerUrl, content);

Solution

  • Instead, you have to add the property one by one to the MultipartFormDataContent.

    content.Add(new StringContent(requestJson.email), "email");
    content.Add(new StringContent(requestJson.userName), "userName");
    content.Add(/* File Content */, "uploadFile", "file3.txt");
    

    You can work with System.Reflection to iterate each property in the RequestJson class as below:

    using System.Reflection;
    
    foreach (PropertyInfo prop in typeof(RequestJson).GetProperties(BindingFlags.Instance|BindingFlags.GetProperty|BindingFlags.Public))
    {
        if (prop.Name == "uploadFile")
        {
            var fileContent = /* Replace with Your File Content */;
    
            content.Add(fileContent, prop.Name, "file3.txt");
        }
        else
        {
            content.Add(new StringContent(JsonConvert.SerializeObject(prop.GetValue(requestJson))), prop.Name);
        }
    }
    

    Demo @ .NET Fiddle