使用多部分/表单数据上传图像

时间:2020-03-17 05:31:04

标签: c# xamarin xamarin.forms

以我的xamarin形式。我正在尝试使用mulipart-formdata发送多个图像和文件。后端的API团队工作给了我这种结构。

enter image description here

如您所见,有一个名为“ notification_files”的参数,它将发送在我的应用程序中使用Media.Plugin和filepicker插件选择的图像和文件。我知道如何以正常方式发送数据。但是如何在xamarin.forms中使用httpclient发送这些格式数据?API团队给了我他们等效的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); 

如何使用HttpClient编写此代码?

我尝试过的事情

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");
            }

DataManager 是我的可观察集合,其中包含选定的图像和文件。

使用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);

希望得到任何帮助。

1 个答案:

答案 0 :(得分:1)

我是这样做的

MultipartFormDataContent multiContent = new MultipartFormDataContent();
            multiContent.Headers.ContentType.MediaType = "multipart/form-data";
            foreach (SelectedDocumentModel model in SelectedFileData)
            {                 
                var upfilebytes = File.ReadAllBytes(model.Path);
                multiContent.Add(new ByteArrayContent(upfilebytes, 0, upfilebytes.Count()), "notification_files", model.FileName);                        
            }
            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);         
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));