Divymital Ответов: 0

Отправка изображения с помощью xamarin media plugin происходит очень медленно


Hi,

I am creating a mobile application to capture image and send on my c# api. The image captured is sent to server very slow and takes about 18-20 sec for 1mb image. Image from rear camera does not even go ! Please assist how what change I shall make in my app.

PFB the code for mobile app and the c# api:

Mobile app code:

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

        if (!CrossMedia.Current.IsTakePhotoSupported && !CrossMedia.Current.IsPickPhotoSupported)
        {

        }
        else
        {

            var check = CrossMedia.Current.IsTakePhotoSupported;
            try
            {

                var options = new StoreCameraMediaOptions()
                {
                    DefaultCamera = CameraDevice.Front,
                    SaveToAlbum = true,
                    Directory = "com.companyname.DemoApp",
                    Name = DateTime.Now.ToString("yyyyMMddTHHmmss") + ".jpg"
                };

                var file = await CrossMedia.Current.TakePhotoAsync(options);


                if (file == null)
                    return;

                MemoryStream memoryStream = new MemoryStream();
                CamPic.Source = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    file.GetStream().CopyTo(memoryStream);
                    return stream;
                });

                PostIntegrationForData(file);
                await DisplayAlert("Done", "Image Posted To Server !", "Ok");
                file.Dispose();
                CamPic.Source = null;
            }
            catch(Exception Ex)
            {
                await DisplayAlert("Error", Ex.Message, "Ok");
                await DisplayAlert("Error", Ex.StackTrace, "Ok");
            }
            //}

        }

    }

    private string PostIntegrationForData(MediaFile argMediaFile)//byte[] argFile)
    {
        string url = string.Format("http://localhost:83/api/MyController/PostFile");            

                    HttpClient httpClient = new HttpClient();
        MultipartFormDataContent form = new MultipartFormDataContent();

        form.Add(new StringContent("Sample Title"), "title");
        form.Add(new StreamContent(argMediaFile.GetStream()), "FileName", argMediaFile.Path);

        HttpResponseMessage response = httpClient.PostAsync(url, form).Result;

        using (HttpContent content = response.Content)
        {
            string data = response.Content.ReadAsStringAsync().Result;
            return data;
        }            
    }
c# API code:

    [HttpPost]
    public HttpResponseMessage PostFile()
    {
        HttpResponseMessage result = null;
        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count > 0)
        {
            var docfiles = new List<string>();
            foreach (string file in httpRequest.Files)
            {
                //string FileName = httpRequest["FileName"];
                string FileName = String.Empty;
                var postedFile = httpRequest.Files[file];
                var postedFileName = postedFile.FileName;
                postedFileName = Path.GetFileName(postedFileName);
                var filePath = HttpContext.Current.Server.MapPath("~/" + postedFileName);

                postedFile.SaveAs(filePath);
                docfiles.Add(filePath);
            }                
            result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
        }
        else
        {
            result = Request.CreateResponse(HttpStatusCode.BadRequest);
        }
        return result;
    } 
Please suggest , I have been struggling with this and could not get a solution for better performance or any way out to send the image in 1 or 2 sec.

Thanks in advance !

Regards,
Divya


Что я уже пробовал:

Я новичок в xamarin и хочу найти решение. Раньше у меня были проблемы с разрешениями камеры и т. д., которые я исправил.

Richard Deeming

HttpResponseMessage response = httpClient.PostAsync(url, form).Result;

Эта линия выглядит подозрительно. Сделайте свой PostIntegrationForData метод async, и использовать await вместо .Result.
private async Task<string> PostIntegrationForData(MediaFile argMediaFile)
{
    string url = string.Format("http://localhost:83/api/MyController/PostFile");            

    HttpClient httpClient = new HttpClient();
    MultipartFormDataContent form = new MultipartFormDataContent();

    form.Add(new StringContent("Sample Title"), "title");
    form.Add(new StreamContent(argMediaFile.GetStream()), "FileName", argMediaFile.Path);

    HttpResponseMessage response = await httpClient.PostAsync(url, form);

    using (HttpContent content = response.Content)
    {
        string data = await response.Content.ReadAsStringAsync();
        return data;
    }
}
...
await PostIntegrationForData(file);
await DisplayAlert("Done", "Image Posted To Server !", "Ok");
...

0 Ответов