July 06, 2015 by Anuraj Estimated read time : 3 mins
.NetASP.NetASP.Net MVCASP.NET Core
In ASP.NET 5 MVC 6 Microsoft changed the File upload feature. Now MVC 6 support model binding of multipart form data, which means, you can include file as the property of your model.
Here is the View code, which helps to upload file.
And here is the model class, with File property, which is a type of IFormFile (from namespace Microsoft.AspNet.Http), which helps to unit test your code as well.ASP.NET Model binding will help to decorate properties with data validation attributes as well.
In the Home controller, I have created an upload action method, with user parameter, this method will helps to save the data and uploads the file to file system.
You need to trim the file name, otherwise ASP.NET will throw argumentException, because filename returns with double quotes like this “filename.txt”, which is not a valid character for a filename. IHostingEnvironment injected to controller, which helps to identify the wwwroot location. For multiple files, you can do the same with List, using loop you can enumerate and save.