Home > OS >  Post request body using file and text using c#
Post request body using file and text using c#

Time:11-30

In 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 some how file upload is happening to the params 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 = "[email protected]";

            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);

CodePudding user response:

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

  • Related