Forum Xamarin Xamarin.Forms

how to post a image from mobile gallery to php server

ShrikantPShrikantP Member ✭✭
edited September 9 in Xamarin.Forms

I'm new to xamarin, i'm trying to make an application that needs to upload an image from mobile gallery to a webservice in PHP, i don't know if i need to save the image in a directory or convert it to a BLOB and save my image in my MySql DB.
following is my code for picking a image:

private async void PickPhoto_Clicked(object sender, EventArgs e)

if (!CrossMedia.Current.IsPickPhotoSupported)
            await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
    var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
            PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,

    if (file == null)

    FileImage.Source = ImageSource.FromStream(() =>
            var stream = file.GetStream();
            return stream;

And Upload the image;

private async void btndone_Clicked(object sender, EventArgs e)
var content = new MultipartFormDataContent();
content.Add(new StreamContent(_mediaFile.GetStream()), "\"file\"", $"\"{_mediaFile.Path}\"");

        var httpClient = new System.Net.Http.HttpClient();
        var url = "";
        var responseMsg = await httpClient.PostAsync(url, content);

        var remotePath = await responseMsg.Content.ReadAsStringAsync();

And i'm getting a error on:-> content.Add(new StreamContent(_mediaFile.GetStream()), "\"file\"", $"\"{_mediaFile.Path}\"");
System.NullReferenceException. Object reference not set to an instance of an object


  • XavierPerseguersXavierPerseguers CHMember ✭✭✭
    edited September 9

    In my app, I'm converting the image as stream of bytes:

                    var stream = await DependencyService.Get<IPicturePicker>().GetImageStreamAsync();
                    if (stream != null)
                        byte[] bytes = null;
                        using (MemoryStream ms = new MemoryStream())
                            bytes = ms.ToArray();
                        // Change the background image right away!
                        viewModel.Person.BackgroundProfileSource = ImageSource.FromStream(() => new MemoryStream(bytes));
                        // and then upload it asynchronously to the server

    and then post as image/jpeg, nothing fancy:

                var contents = new ByteArrayContent(bytes);
                if (!string.IsNullOrEmpty(accessToken))
                    contents.Headers.Add("X-Authorization", accessToken);
                contents.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                string responseBody = null;
                HttpResponseMessage response = null;
                    response = await Client.PostAsync(requestUri, contents);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    responseBody = await response.Content.ReadAsStringAsync();
                catch (HttpRequestException hre)

    The PHP part is straightforward and well-documented on the internet:

    $imageBytes = file_get_contents('php://input');
    $tempName = tempnam('profile') . '.jpg';
    file_put_contents($tempName, $imageBytes);
  • XavierPerseguersXavierPerseguers CHMember ✭✭✭

    You could as well search for a similar question and find this post from 2017 which is even in the list of recently updated posts:

Sign In or Register to comment.