I am trying to upload some files from a console application to an ASP.NET 5 WEB API service.
Client (console app):
private static HttpResponseMessage UploadFiles(string[] files, Uri uploadEndpoint)
{
var message = new HttpRequestMessage();
var content = new MultipartFormDataContent();
foreach (var file in files)
{
var fs = new FileStream(file, FileMode.Open);
var index = file.LastIndexOf(@"\");
var fn = file.Substring(index + 1);
fs.Position = 0;
content.Add(new StreamContent(fs), "file", fn);
}
message.Method = HttpMethod.Post;
message.Content = content;
message.RequestUri = uploadEndpoint;
var client = new HttpClient();
return client.SendAsync(message).Result;
}
Server (Asp.Net 5) Web API
[HttpPost("upload")]
public IActionResult UploadFiles(ICollection<IFormFile> files)
{
var streams = files.Select(f => f.OpenReadStream()).ToArray();
var names = files.Select(f => ContentDispositionHeaderValue.Parse(f.ContentDisposition).FileName).ToArray();
ProcessFiles(streams, names);
return new HttpOkResult();
}
Unfortunately the collection of IFormFile is always empty. Anyone can tell me why?
Thanks
Manu
Your upload controller expects the name identifier of the posted data to be files, not file.
This line: content.Add(new StreamContent(fs), "file", fn);
should be: content.Add(new StreamContent(fs), "files", fn);
So your code basically works, it was just a simple mistake.
You need to set the enctype of the form to multipart/form-data. Something like this.
<form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data">
<input type="file" name="files" multiple/>
<input type="submit" value="Upload" />
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With