xamarin.forms-使用多部分/表单数据上传多个图像和文件

时间:2020-03-13 04:23:17

标签: xamarin xamarin.forms plugins

在我的xamarin.forms应用中。我正在使用Media.plugin从图库和相机中选择图像,还使用文件选择器插件从文件管理器中选择pdf,jpg等文件。用户可以选择多个图像和文件,并将其存储在一个可观察的集合中。集合我有图像和文件的路径。卡住的地方是我想通过使用multipart / form数据将这些数据发送到rest API。如何将这些多个文件发送到服务器?任何帮助表示赞赏。

我的ObservableCollection

  public ObservableCollection<SelectedDocumentModel> DataManager
        {
            get
            {
                return _selectedfile ?? (_selectedfile = new ObservableCollection<SelectedDocumentModel>());
            }
        }

我的数据模型

   public class SelectedDocumentModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }



        public string FileName { get; set; }
        public string Path { get; set; }
        public ImageSource SelectedImage { get; set; }
        public object Tasks { get; internal set; }

        private bool isLoadingVisible = false;
        public bool IsLoadingVisible
        {

            get
            {
                return isLoadingVisible;
            }

            set
            {
                if (value != null)
                {
                    isLoadingVisible = value;
                    NotifyPropertyChanged("IsLoadingVisible");
                }
            }
        }     
    }

使用media.plugin选择图像并将其分配给我的可观察集合

 var Filename = Path.GetFileName(file.Path);
                            var FilePath = file.Path;
                            var newList = new SelectedDocumentModel()
                            {
                                FileName = Filename,
                                SelectedImage = imageSource,
                                IsLoadingVisible = false,
                                Path = FilePath
                            };
                            DataManager.Add(newList);

使用filepicker插件从文件管理器中选择文件并分配给observablecollection

var FilePath = pickedFile.FilePath;
                                var newList = new SelectedDocumentModel()
                                {
                                    FileName = filename,
                                    SelectedImage = imageSource,
                                    IsLoadingVisible = false,
                                    Path= FilePath
                                };
                                DataManager.Add(newList);

编辑

这是我应该使用httpclient进行的操作。目前,这些都是使用RestSharp编写的。

var client = new RestClient("{{api_url}}/MYData");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "bearer {{token}}");
request.AddHeader("Content-Type", "application/json");
request.AlwaysMultipartFormData = true;
request.AddParameter("ids", " [{\"id\":1,\"person_id\":5}]");
request.AddParameter("title", " Test");
request.AddParameter("description", " Test");
request.AddParameter("send_text_message", " true");
request.AddParameter("text_message", " Test");
request.AddParameter("notification_type"," global");
request.AddParameter("my_files", "[
  { 
  \"name\": \"abc.jpg\",
  \"key\": \"1583307983694\"
}
]");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

我是通过卢卡斯·张(Lucas Zhang)建议的方式完成的-MSFT

try {
                MultipartFormDataContent multiContent = new MultipartFormDataContent();
                foreach (SelectedDocumentModel model in SelectedFileData)
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(model.Path);
                    MemoryStream stream = new MemoryStream(byteArray);
                    HttpContent fileStreamContent1 = new StreamContent(stream);
                    fileStreamContent1.Headers.ContentDisposition = new
                    System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                    {
                        Name = model.FileName,
                        FileName = model.FileName
                    };
                    fileStreamContent1.Headers.ContentType = new
                    System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    multiContent.Add(fileStreamContent1);
                }

                multiContent.Add(new StringContent(notificationdetails[0]), "title");
                multiContent.Add(new StringContent(notificationdetails[1]), "description");
                multiContent.Add(new StringContent(notificationdetails[3]), "type");
                multiContent.Add(new StringContent(notificationdetails[7]), "send_text_message");
                multiContent.Add(new StringContent(notificationdetails[2]), "text_message");
                multiContent.Add(new StringContent(notificationdetails[8]), "send_email");
                multiContent.Add(new StringContent(notificationdetails[9]), "notification_type");

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("bearer",Settings.AuthToken);          
                var response = await client.PostAsync(url, multiContent);
                var responsestr = response.Content.ReadAsStringAsync().Result;
                await DisplayAlert("Result", responsestr.ToString(), "ok");


            }
            catch (Exception ex)
            {
                await DisplayAlert("Result", ex.Message.ToString(), "ok");
            }

很遗憾,它无法正常工作。它没有按我的预期发送数据。

如何在单击按钮时将每个文件作为多部分/表单数据上传。需要任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用 MultipartFormDataContent 添加多个图像,并使用ContentDispositionHeaderValue.Parameters添加数据的值。

用法

var fileStream = pickedFile.GetStream();
var newList = new SelectedDocumentModel()
                                {
                                    FileName = filename,
                                    SelectedImage = imageSource,
                                    IsLoadingVisible = false,
                                    Path= FilePath,
                                    Data = fileStream ,
                                };

MultipartFormDataContent multiContent = new MultipartFormDataContent();


foreach(var SelectedDocumentModel model in DataManager)
{
  HttpContent fileStreamContent1 = new StreamContent(model.Data);
  fileStreamContent1.Headers.ContentDisposition = new 
  System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") 
  {
     Name = "File", 
     FileName = "xxx.jpg" 
  };
  fileStreamContent1.Headers.ContentType = new 
  System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
  multiContent.Add(fileStreamContent1);


  multiContent.Add(new StringContent(model.Title), "model.Title");
  multiContent.Add(new StringContent(model.Description), "model.Description");
  multiContent.Add(new StringContent(model.Detail), "model.Detail");  
}

// Send (url = url of api) ,use httpclient
var response = await client.PostAsync(url, multiContent);