Search code examples
c#apiweb-servicesxamarindotnet-httpclient

Upload image from mobile app to API with multipart/form-data


I have this API where I receive an image to save it in a storage server. I've been testing the functionality in postman and works perfectly fine. But when it comes to the mobile app it does not send the image.

here you can see the Postman POST request

the code for the xamarin app is the next

        var content = new MultipartFormDataContent();
        var stream = File.OpenRead(_mediaFile.Path);
        var streamcontent = new StreamContent(stream);
        content.Add(streamcontent, "picture");
        var client = new HttpClient();
        HttpResponseMessage response = await cliente.PostAsync($"http://localhost:200/api/.../picture", content);
        string result = response.Content.ReadAsStringAsync().Result; 
        Response responseData = JsonConvert.DeserializeObject<Response>(result);
        if (response.IsSuccessStatusCode)
        {
            await Application.Current.MainPage.DisplayAlert("Correcto", "Imagen subida Correctamentel!", "OK");
            _mediaFile = null;
            terminado.IsEnabled = true;
        }
        else
        {
            terminado.IsEnabled = true;
            await Application.Current.MainPage.DisplayAlert("Error", "Opps algo ocuirrio mal!", "OK"); }

As you can see in the postman the key picture receives the image name. I tried it also with curl and it works:

curl -X POST "http://localhost:200/api/.../picture" -H  "accept: application/json" -H  "Content-Type: multipart/form-data" -F "picture=@version1.jpeg;type=image/jpeg"

Solution

  • I've managed it to work, but using RestSharp library instead of HttpClient:

    var client = new RestClient("192.168.0.2"); //the ip of your REST API
    var request = new RestRequest(Method.POST); 
    request.AddHeader("Content-Type", "multipart/form-data"); // I'm using multipart form data
    request.AddHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLC"); // using JWT for auth
    request.AddFile("pictureField", "/path/to/file"); //the path depends on which device you're using
    IRestResponse response = client.Execute(request); 
    

    Pretty much straigt forward and works perfectly fine. Also, the "pictureField" depends on the name of the field the API requires, and the path to file should not be hardcoded. It should be given depending on where in the device the choosen image is.