Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When uploading files to ASP.Net 5 Web API, the collection of IFormFile is empty

Tags:

asp.net-core

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

like image 270
Manu Cohen Yashar Avatar asked Dec 31 '15 13:12

Manu Cohen Yashar


2 Answers

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.

like image 70
Dan Lewi Harkestad Avatar answered Oct 24 '22 00:10

Dan Lewi Harkestad


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>
like image 36
Anuraj Avatar answered Oct 24 '22 00:10

Anuraj