如何在xamarin表单Android中从MultipartFormDataContent中删除图像?

hwazgwia  于 2022-12-07  发布在  Android
关注(0)|答案(1)|浏览(167)

我在C# Xamarin Forms Android中使用此代码

MultipartFormDataContent content = new MultipartFormDataContent();
 private async void Scanner()
    {
        var scannerPage = new ZXingScannerPage();
        scannerPage.Title = "scanner";

        scannerPage.OnScanResult += (result) =>
        {
            scannerPage.IsScanning = false;
            string resultado = Convert.ToString(result);
            if (resultado.Contains("http") || resultado.Contains("https"))
            {
                Browser.OpenAsync(resultado, BrowserLaunchMode.External);
                Navigation.PopAsync();
            }
            else
                Device.BeginInvokeOnMainThread(async () =>
                {
                    Navigation.PopAsync();
                    //Hace el display del valor obtenido
                    subs = result.Text.Split('\t');
                    string cadena = "var1N°: " + subs[0] + "\nvar2 N°: " + subs[1] + "\nvar3 N°: " + subs[2];
                    await this.DisplayAlert("Datos del QR", cadena, "OK");
                    sacarFotos();
                });
        };
        await Navigation.PushAsync(scannerPage);
        
    }
    private async Task<bool> GetResultFromAlert()
    {
        return await this.DisplayAlert("Test", "Message", "Ok", "Cancel");
    }
    private Task DisplayAlert(string v1, string v2)
    {
        throw new NotImplementedException();
    }

    private async void TakePhotos()
    {
        var file2 = await MediaPicker.CapturePhotoAsync();
        
        while (file2 != null)
        {
            Image im = new Image();
            im.ClassId = contador.ToString();
            im.Source = ImageSource.FromFile(file2.FullPath);
            im.HeightRequest = 600;
            im.WidthRequest = 600;
            im.MinimumHeightRequest = 600;
            im.MinimumWidthRequest = 600;
            im.VerticalOptions = LayoutOptions.End;
            im.HorizontalOptions = LayoutOptions.End;
            im.Aspect = Aspect.AspectFill;

            imgs.Children.Add(im);

            Button deleteButton = new Button();
            deleteButton.Text = "Delete image";
            deleteButton.VerticalOptions = LayoutOptions.CenterAndExpand;
            deleteButton.HorizontalOptions = LayoutOptions.Center;
            deleteButton.MinimumWidthRequest = 100;
            deleteButton.ClassId = contador.ToString();
            deleteButton.Clicked += async (sender, args) => {
                imgs.Children.Remove(im);
                imgs.Children.Remove(deleteButton);
            };
            imgs.Children.Add(deleteButton);

            content.Add(new StreamContent(await file2.OpenReadAsync()), "file", subs[0] + "_" + subs[1] + "_" + subs[2] + "_" + contador + "_" + file2.FileName);
            
            file2 = await MediaPicker.CapturePhotoAsync();
            
            contador++;
        }
        
        btnScannerQR.IsVisible = false;
        btnSacarFotos.IsVisible = true;
        btnEnviarImagenes.IsVisible = true;
    }

    private async void enviarFotos()
    {
        bool answer = await DisplayAlert("¿Have you finished?", "¿are you sure you want to send the images?", "Yes", "No"); 
        
        if(answer)
        {

            //////////////////////////////////////////
            /// algorithm to remove deleted images ///
            //////////////////////////////////////////

            var httpClient = new HttpClient();
            var response = await httpClient.PostAsync("url", content);
            string res = await response.Content.ReadAsStringAsync();
            await DisplayAlert("Result", res, "OK");

            btnSacarFotos.IsVisible = false;
            btnEnviarImagenes.IsVisible = false;
            btnScannerQR.IsVisible = true;
            content = null;
            imgs.Children.Clear();

            Shell.Current.GoToAsync($"//{nameof(HomePage)}");
        }
        else
        {
            // lblStatus.Text = "Nothing sent";
        }

所以,我动态地创建图像和按钮,也可以从显示中删除它们,但是当用户发送图像时,我不能从MultipartFormDataContent中删除它们。有人知道如何从MultipartFormDataContent中删除图像吗?非常感谢。

kwvwclae

kwvwclae1#

解决方案

嗯,基本上我在发送图片之前添加了所有的东西。我把我的代码留在这里。也许能帮助别人。

string[] subs;
MultipartFormDataContent content = new MultipartFormDataContent();
MultipartFormDataContent content2 = new MultipartFormDataContent();
List<StreamContent> listStreamContent = new List<StreamContent>();
List<string> listImgName = new List<string>();
List<string> ControlCantName = new List<string>();
List<int> listDelete = new List<int>();

private async void TakePhotos()
{
    try
    {
        bool answer = await DisplayAlert("¿Have you finished?", "¿are you sure", "Yes", "No"); 

        if(answer)
        {
            int contImgBorradas;
            if (listDelete.Count > 0 || listDelete != null)
            {
                foreach (var num in listDelete)
                {
                    contImgBorradas = 1;
                    foreach (var img in ControlCantName)
                    {
                        if (num == contImgBorradas)
                        {
                            listImgName.Remove(num - 1);
                            listStreamContent.Remove(num - 1);
                        }
                        contImgBorradas++;
                    }
                }
            }

            for (int x = 0; x < listStreamContent.Count; x++)

            {
                content2.Add(listStreamContent[x], "file", listImgName[x]);
            }

            var httpClient = new HttpClient();
            var response = await httpClient.PostAsync("url", content2);
            // lblStatus.Text = await response.Content.ReadAsStringAsync();
            string res = await response.Content.ReadAsStringAsync();
            await DisplayAlert("Resultado", res, "OK");

            btnSacarFotos.IsVisible = false;
            btnEnviarImagenes.IsVisible = false;
            btnScannerQR.IsVisible = true;
            content = null;
            content2 = null;
            imgs.Children.Clear();

            await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
        
        }
    }
    catch(Exception ex)
    {
        await DisplayAlert("Error", "sorry, we had a problem. Try again.", "OK");
        await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
    }
}

相关问题