Anand
Anand

Reputation: 1959

Upload images using multipart/form data

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.

enter image description here

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

How can I write this using HttpClient?

What I have tried

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 is my observable collection contains images and files selected.

Selecting image using media.plugin and allocating to my observable collection

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

Any help is appreicted.

Upvotes: 0

Views: 3318

Answers (1)

Anand
Anand

Reputation: 1959

I done it like this

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

Upvotes: 1

Related Questions