Search code examples
apixamarinstrapi

Upload an image to Strapi using Xamarin.Forms


Currently im working on a xamarin forms app, that upload image to Strapi API. To take a picture from the camera i'm using CrossMedia Plugin

var photo = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions() { PhotoSize= PhotoSize.Small, CompressionQuality = 100 });

if (photo != null)
   ProductPic.Source = ImageSource.FromStream(() => { return photo.GetStream(); });

than send the photo in post Method :

 HttpClient httpClient = new HttpClient();
 MultipartFormDataContent mt = new MultipartFormDataContent();
 photo.GetStream().Position = 0;
 StreamContent imagePart = new StreamContent(photo.GetStream());
 imagePart.Headers.Add("files", "jpg");
 mt.Add(imagePart, string.Format("image"), string.Format("bsk.jpeg"));

 var response = await httpClient.PostAsync("http://111.111.111.111:2222/upload", mt);

The problem that im facing this error

"{\"statusCode\":400,\"error\":\"Bad Request\",\"message\":\"Bad Request\",\"data\":{\"errors\":[{\"id\":\"Upload.status.empty\",\"message\":\"Files are empty\"}]}}


Solution

  • The error points the image part is empty , try to replace StreamContent with ByteArrayContent , send ByteArray instead of Stream .

    HttpClient httpClient = new HttpClient();
    MultipartFormDataContent mt = new MultipartFormDataContent();
    mt.Headers.ContentType.MediaType = "multipart/form-data";
    var upfilebytes = File.ReadAllBytes(photo.Path);
    mt.Add(new ByteArrayContent(upfilebytes, 0, upfilebytes.Count()), string.Format("image"), string.Format("bsk.jpeg"));
    
    var response = await httpClient.PostAsync("http://111.111.111.111:2222/upload", mt);
    

    Refer to

    https://stackoverflow.com/a/61095848/8187800.