使用多部分/表单数据上传图像 [英] Upload images using multipart/form data

查看:115
本文介绍了使用多部分/表单数据上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以我的xamarin形式.我正在尝试使用mulipart-formdata发送多个图像和文件.后端的API小组工作为我提供了这种结构.

In my xamarin forms. I am trying to send multiple images and files using mulipart-formdata.The API team work on back end gave me this structure.

如您所见,有一个名为"notification_files"的参数,它将发送使用我的应用程序中的Media.Plugin和filepicker插件选择的图像和文件.我知道如何以正常方式发送数据.但是如何在xamarin.forms中使用httpclient发送这些格式数据?API团队给了我他们等效的Restsharp代码:

As you can see there is a parameter called "notification_files" which will send images and files selected using Media.Plugin and filepicker plugin in my app. I know how to send data in normal way. But how can I send these formadata using httpclient in xamarin.forms?The API team gave me their equivalent Restsharp code:

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编写此代码?

How can I write this using 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 是我的可观察集合,其中包含选定的图像和文件.

DataManager is my observable collection contains images and files selected.

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

希望得到任何帮助.

推荐答案

我是这样做的

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

这篇关于使用多部分/表单数据上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆