0

I need to make a POST call from my Xamarin forms app where I need to upload a file object as it is to API using POST Call. Is there any way to make it possible?

TylerH
  • 20,799
  • 66
  • 75
  • 101

2 Answers2

1

if you send file object using Base64 or Byte[] then it will allowed only limited may be upto 2-4 Mb but if you have a larger image than that it will not support.

So, Solution is Post Stream Content Like,

var file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
            {
                PhotoSize = PhotoSize.Full,
                CompressionQuality = 100
            });

Create Object of MediaFile like, public MediaFile AttachedImage; and Store file into it so Memory stream will not lost. Like,AttachedImage = file

Post Code on API,

HttpClient httpClient = new HttpClient();
MultipartFormDataContent mt = new MultipartFormDataContent();
AttachedImage.GetStream().Position = 0;
StreamContent imagePart = new StreamContent(AttachedImage.GetStream());
imagePart.Headers.Add("Content-Type", ImageType);
mt.Add(imagePart, String.Format("file"), String.Format("bk.jpeg"));

requestMessage.Content = mt;


var response = await httpClient.PostAsync("Your URL", mt);
if (response.IsSuccessStatusCode)
{
    var responseString = await response.Content.ReadAsStringAsync();
    var objRootObjectuploadImage = JsonConvert.DeserializeObject<RootObjectuploadImage>(responseString);
    if (objRootObjectuploadImage != null)
    {

    }
    else
    {

    }
}
else
{
    Loading(ActIndicator, false);
    await DisplayAlert(res.LAlert, "webserver not responding.", res.LOk);
}
Krunal Bagadia
  • 419
  • 2
  • 8
-1

NO, it is not possible to send file object. You can send as a json by converting the file in the Base64 string. This is the advised proven solution. This link has code for converting back and forth from Base64.

Abdul Gani
  • 679
  • 3
  • 7