Please find the below sample code to send multiple files to .Net web api via post method
.Net Web API method
[HttpPost]
public string SaveImage()
{
string uploadedfilelist="";
if (((IList)HttpContext.Current.Request.Form.AllKeys).Contains("fileModel"))
{
var activity = JsonConvert.DeserializeObject<SocialCompanyPost>(HttpContext.Current.Request.Form["fileModel"]);
var files = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files : null;
if (files != null && files.Count > 0)
{
for (int i = 0; i < files.Count; i++)
{
if (files[i].ContentLength > 0)
{
try
{
var filepath = HttpContext.Current.Server.MapPath("~/Images/ServiceCenters/" + files[i].FileName);//, ms.ToArray());
files[i].SaveAs(filepath);
uploadedfilelist += files[i].FileName+",";
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}
}
return uploadedfilelist;
}
Client side MVC application post method to call web api post method
public string UploadImages(ServiceCenterPost socialCompany)
{
var url = "api/Images/SaveImage";
if (socialCompany.ThumbnailUrlFileUpload.Count() > 0)
{
var fullURL = ConfigurationManager.AppSettings["ServiceApi"] + url;
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
var stringContent = new StringContent(JsonConvert.SerializeObject(new SocialCompanyAdmin { CompanyCode = socialCompany.CompanyCode }));
stringContent.Headers.Add("Content-Disposition", "form-data; name=\"fileModel\"");
form.Add(stringContent, "json");
//loop each files from file upload control
foreach (var file in socialCompany.ThumbnailUrlFileUpload)
{
if (file != null && file.ContentLength > 0)
{
var streamContent = new StreamContent(file.InputStream);
streamContent.Headers.Add("Content-Type", "application/octet-stream");
streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(file.FileName) + "\"");
form.Add(streamContent, "file", Path.GetFileName(file.FileName));
}
}
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("Accept-Language", Language);
var response = client.PostAsync(fullURL, form).Result;
if (response.IsSuccessStatusCode)
{
string modelObject = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<string>(modelObject);
}
}
return null;
}