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");
            return;
        }
    var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
        {
            PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,

        });
    if (file == null)
       return;

    FileImage.Source = ImageSource.FromStream(() =>
        {
            var stream = file.GetStream();
            file.Dispose();
            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 = "http://abcd.xyz/tsb/img";
        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

Answers

  • 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())
                        {
                            stream.CopyTo(ms);
                            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
                        viewModel.UpdateBackgroundImage(bytes);
                    }
    

    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;
    
                try
                {
                    response = await Client.PostAsync(requestUri, contents);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    response.EnsureSuccessStatusCode();
                    responseBody = await response.Content.ReadAsStringAsync();
                    response.Dispose();
                }
                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: https://forums.xamarin.com/discussion/93576/post-image-to-server#latest

Sign In or Register to comment.