Abhi Abhi - 1 year ago 350
C# Question

Can we pick a Image from Phone (Android / iOS) and upload it to server with common code(Xamarin Forms)?

to achieve this should I go for platform specific code or Can I do that from common code in shared Project of Xamarin.Forms.

Basically I need to open Gallery and pick a image and then upload it to server in multipart byte array.

Couldn't found any examples using Xamarin Forms.

Answer Source

I am assuming you are using a PCL solution.

There are quite a few ways to do this. Here is the plugin that I used to allow the user to pick an image from the gallery and then do something with that image.

Though you could also use XLabs version as well, available here.

With the plugin I suggested, after installing it into the PCL project, the Android project, and the iOS project, you could write code like this to show an image picker and then do something with that image:

public List<string> Uris;

private ObservableCollection<MediaFile> _images;
public  ObservableCollection<MediaFile> Images {
    get { return _images ?? (_images = new ObservableCollection< MediaFile >()); }
    set {
        if(_images != value) {
            _images = value;

/// <summary>
/// Allows the user to pick a photo on their device using the native photo handlers and returns a stream, which we save to disk.
/// </summary>
/// <returns>string, the name of the image if everything went ok, 'false' if an exception was generated, and 'notfalse' if they simply canceled.</returns>
public async Task<string> PickPictureAsync() {

    MediaFile file      = null;
    string    filePath  = string.Empty;
    string    imageName = string.Empty;

    try {
        file = await CrossMedia.Current.PickPhotoAsync();

        #region Null Check

         if(file == null) { return null; }                                                                                 //Not returning false here so we do not show an error if they simply hit cancel from the device's image picker


        imageName = "SomeImageName.jpg";
        filePath  = /* Add your own logic here for where to save the file */ //_fileHelper.CopyFile(file.Path, imageName);
    } catch(Exception ex) {
         Debug.WriteLine("\nIn PictureViewModel.PickPictureAsync() - Exception:\n{0}\n", ex);                           //TODO: Do something more useful
         return null;
    } finally { if(file != null) { file.Dispose(); } }



    return imageName;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download