Forum Xamarin.Forms

Extremely simple image upload keeps timing out

Hello, I've spent out try to figure out why my image upload keeps timing out. Everything has worked before but i seem to be struggling on something trival.

here is my post to my web api

byte[] ImageUploadBase64;

    private async void Button_Clicked(object sender, EventArgs e)
        await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            await DisplayAlert("No Camera", ":( No camera available.", "OK");

        var file = await CrossMedia.Current.PickPhotoAsync();
        if (file == null)

        using (var memoryStream = new MemoryStream())
            var myfile = memoryStream.ToArray();
            ImageUploadBase64 = myfile;

        var check = await UploadTheImage();

    public async Task<HttpResponseMessage> UploadTheImage()
        Stream stream = new MemoryStream(ImageUploadBase64);
        var FixedFileName = DateTime.Now.Millisecond + "PhotoDocument" + "1234" + ".jpg";

        StreamContent scontent = new StreamContent(stream);
        scontent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            FileName = FixedFileName,
            Name = "image"

        scontent.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
        var client = new HttpClient(new NativeMessageHandler());
        var multi = new MultipartFormDataContent();


        client.BaseAddress = new Uri("myUrl");

        HttpResponseMessage result = await client.PostAsync("api/UploadImage/", multi).ConfigureAwait(false);

       // var ResultResponse = await result.Content.ReadAsStringAsync();

        return result;

and my endpoint which im just trying to save the image to disk

public Task ImageUpload()
if (!Request.Content.IsMimeMultipartContent())

            return null;


            string root = HttpContext.Current.Server.MapPath("~/Files/Photos");
            var provider = new CustomMultipartFormDataStreamProvider(root);

            var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
                if (t.IsFaulted || t.IsCanceled)
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                foreach (MultipartFileData uploadedFile in provider.FileData)

                    string path = provider.FileData[0].LocalFileName;
                    int pos = path.LastIndexOf("\\") + 1;
                    string GeneratedFileName = path.Substring(pos, path.Length - pos);

                   // var UpdateGoal = db.UserGoals.SingleOrDefault(x => x.UserID == GetUser.ID && x.UserGuid == UserGuid && x.ID == NewGoalID);

                    using (Image image = Image.FromFile(root + "\\" + GeneratedFileName))
                        using (MemoryStream m = new MemoryStream())
                            image.Save(m, image.RawFormat);
                            byte[] imageBytes = m.ToArray();

                                // Convert byte[] to Base64 String
                              string base64String = Convert.ToBase64String(imageBytes);

                            //UpdateGoal.GoalImageFile = base64String;
                            //UpdateGoal.GoalImageUrl = "url" + GeneratedFileName;
                            //UpdateGoal.GoalTypeID = 2;




                return Request.CreateResponse(HttpStatusCode.OK);

            return task;


the task just continues to cancel after a minute, ive also tried extending the HttpClient Timeout which has no affect. I've tried with smalled sized images, and checking the image that i select is a max of 500k so its not that the image is too large.

any ideas??


  • N_BauaN_Baua INMember ✭✭✭✭✭

    @CostasAletrari ,

    You can create a Base64 string of your image and stream it via service (make sure you have enough buffer configured as to the requirement.)

    Try uploading the image as under: (App Level Logic)

    using (var client = new HttpClient())
            var imageContent = new MultipartFormDataContent
            { new StringContent(Base64String), "ImageData" }
            var httpClient = new HttpClient();
            var imageResponse = await httpClient.PostAsync("YOUR SERVICE URL", imageContent);
            var resultImageContent = imageResponse.Content.ReadAsStringAsync().Result;
            ServiceResult objImageResult = JsonConvert.DeserializeObject<ServiceResult>(resultImageContent);
            if (objImageResult != null)
            //Show some success message

    Update your service to accommodate the Base64 string from device and convert it back to Image on server.

    Hope it helps.

    N Baua

  • SagarPanwalaSagarPanwala USMember ✭✭✭

    @N_Baua : what does this means?
    (make sure you have enough buffer configured as to the requirement.)
    Are you sure just to make Base64 instead of Byte[] will solve the problem?

    @CostasAletrari : Did you get resolution ?

  • N_BauaN_Baua INMember ✭✭✭✭✭


    Are you sure just to make Base64 instead of Byte[] will solve the problem? ==
    Yes, I had implemented this as a working solution, uploading image as Base64 string sorted me out.

    make sure you have enough buffer configured as to the requirement ==
    On server side make sure your service does not fail, have enough capacity to hold data chunks, does not time out etc.

    Hope it helps.

    • N Baua
Sign In or Register to comment.