Search code examples
asp.net-corexamarin.net-corehttpclientdotnet-httpclient

Have to upload image with registration form data using HttpClient C#


I have .Net Core 3.1 Api end point which takes UserData as [FromForm].

I am uploading here image also, which running fine using postman. Image uploading and UserData inserting into DB.

But when I am calling HttpClint.PostAsync then its not working, while I am using MultipartFormDataContent();

EndPoing Signtature of API:

public async Task<IActionResult> SaveUser([FromForm] UserData usr) 
{}

Image Upload code at Xamarin side:

  private async Task UploadFileMedia()
    {
        Constant.mediaFile = null;
        await CrossMedia.Current.Initialize();
        Constant.mediaFile = await CrossMedia.Current.PickPhotoAsync();

        if (Constant.mediaFile is null)
            return;
    }

Http Client Hit:

var requestContent = new MultipartFormDataContent()
                    {

                    new StringContent(JsonConvert.SerializeObject(dictionary), Encoding.UTF8, "application/json"),
                        {new StreamContent(Constant. mediaFile.GetStream()),
                            "\"file\"",
                            $"\"{Constant.mediaFile.Path}\""}
                    };
                    requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    requestContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");


 var response = await client.PostAsync("api/user/save", requestContent);

Solution

  • If you'd like to make request with both image file(s) and json data to your ASP.NET Core API backend, you can refer to the following code snippet.

    requestContent.Add(new StringContent(JsonConvert.SerializeObject(dictionary), Encoding.UTF8, "application/json"), "Prop1");
    requestContent.Add(new StreamContent({your_filestream_here}), "file", System.IO.Path.GetFileName(filepath));
    
    
    var response = await client.PostAsync("/api/user/save", requestContent);
    

    UserData class

    public class UserData
    {
        public string Prop1 { get; set; }
        public IFormFile file { get; set; }
    }
    

    Test Result

    enter image description here