How To Upload File/Image Using Multipart/Form-Data From Client Side To Server? – Client Side (Part 2)
In this post, i am going to explain how to send mutipart/form-data from client side.
A HTTP multipart request helps to send files/images and data over to a HTTP server. It is a very common approach used by browsers and any other HTTP clients to upload files to the server.
using System.Linq;
using System.Net.Http;
using Xamarin.Forms;
namespace ClientApi
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
/// <summary>
/// Purpose: Post multipart data i.e. image or file
/// </summary>
protected async void SaveAttachment(byte[] attachment, string fileName, string attachmentType, string orgFileName)
{
try
{
using (var httpClient = new HttpClient())
{
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(attachmentType), "AttachmentType");
form.Add(new StringContent(orgFileName), "FileName");
if (attachment != null)
form.Add(new ByteArrayContent(attachment, 0, attachment.Count()), "ByteData", fileName);
HttpResponseMessage response = await httpClient.PostAsync("http://yoursiteurl/UploadFileOrImage", form);
string message = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine(message);
}
else
await DisplayAlert("", message, "OK");
}
}
catch (Exception ex)
{
await DisplayAlert("", ex.Message, "OK");
}
}
}
}
If you have any problems or feedback or any idea leave a comment.
Comments
Post a Comment