How to send multipart/form-data to ASP.NET Core Web API?
Maybe you should try decorate controller input and model with [FromForm]
attribute?
See more info here: web api parameters binding.
In given example your controller action should look like this:
[HttpPost("/api/account"), Authorize]
public void SaveUser([FromForm]UserModel info)
In model:
[FromForm(Name="avatar")]
public IFormFile Avatar { get; set; }
[FromForm(Name="name")]
public string Name { get; set; }
1-send multi part file
[HttpPost, Route("postimagenews")]
public IActionResult PostImageNews([FromForm] IFormFile file)
{
try
{
if (file == null || file.Length == 0)
{
return BadRequest("Please send a photo");
}
//create unique name for file
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
//set file url
var savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/news", fileName);
using (var stream = new FileStream(savePath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok(fileName);
}
catch
{
return BadRequest("error in upload image");
}
}
2-recive multi part file
public static async Task<string> PostImage(string apiendpoint, IFormFile data)
{
using (var httpClient = new HttpClient())
{
var multipartContent = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(GetFileArray(data));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
multipartContent.Add(fileContent, "file",data.FileName);
var resultUploadImage= await httpClient.PostAsync(apiendpoint, multipartContent);
if (resultUploadImage.IsSuccessStatusCode)
{
var fileName=(await resultUploadImage.Content.ReadAsStringAsync()).Replace("\"", "");
return fileName;
}
return "";
}
}
public static byte[] GetFileArray(IFormFile file)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
return ms.ToArray();
}
}
3-send file multi part with postman