简体   繁体   中英

How to send File Object to Web api using POST call in Xamarin forms.?

我需要从我的xamarin表单应用程序进行POST调用,我需要使用POST调用将File对象直接上传到API。有什么方法可以实现这一点。

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM