【问题标题】:Upload images using multipart/form data使用多部分/表单数据上传图像
【发布时间】:2020-03-17 05:31:04
【问题描述】:

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

如您所见,有一个名为“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 是我的 observable 集合,包含选定的图像和文件。

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

欢迎任何帮助。

【问题讨论】:

  • 您是否尝试以具有有效键值的字节 [] 格式发送这些图像。在 for 循环中添加那些图像路径和名称。我实现了在多部分中使用单张图片上传的数据; byte[] byteImageFile = ImageFileToByteArray(imagePath); multiForm.Add(new ByteArrayContent(byteImageFile, 0, byteImageFile.Count()), "Your-Key", imagename);
  • @Prasanth Bro 我没明白
  • 据我了解,您想在“notification_files”键中上传这些图像。那么你可以尝试上面的代码吗 - multiContent.Add(new StringContent(notificationdetails[9]), "notification_type");行
  • 尝试类似的方法; multiContent.Add(new StringContent(notificationdetails[9]), "notification_type"); byte[] byteImageFile = ImageFileToByteArray(imagePath); multiContent.Add(new ByteArrayContent(byteImageFile, 0, byteImageFile.Count()), "notification_files", imagename);无论如何,您已经有了图像路径及其名称
  • @Prasanth Bro 问题是,我需要上传多张图片。

标签: c# xamarin xamarin.forms


【解决方案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"));

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 2015-06-19
    • 1970-01-01
    • 2023-03-23
    • 2017-01-10
    • 2019-05-31
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多