Monday, March 7, 2016

ASP.NET Core MVC 6: Uploading File(s)

In previous versions of ASP.NET, an uploaded file was represented by an instance ofSystem.Web.HttpPostedFileBase. This has been replaced in ASP.NET 5 (Core 1.0) by IFormFile, which is found in theMicrosoft.AspNet.Http namespace or Microsoft.Extensions.PlatformAbstractions package. It shares a few of the same properties and methods as its predecessor, but it also has its differences, as shown by example.
  • Firstly we create a ViewModel for our Form:As we can see our ViewModel contains an IFormFile object named ProductImage which will be used to create a file upload input field using ASP.NET Tag Helpers in our Create View.
  • Then Create our actual Form in Create.cstml
  • Now we move to our Products Controller: Now in in the above file as you can see I've used the repository Pattern with Entity Framework 7 (ORM). What it actually does is that it creates an abstraction layer between your code & ORM, so that whenever you want to change your ORM you can do that without any changes in our application code (To learn more about this Click Here). Now to the real topic, In the Constructor of our controller class we use an IApplicationEnvironment the purpose of which is to get the base path of our Web Application (there is no Server.MapPath available so we can't use "~" in our URLs to get the root of our Web Application). The ContentDispositionHeaderValue Class is used to get the ContentDisposition property of the IFormFile object. With this property we get the absolute path of the file that the user uploaded e.g. "C:\\Users\\Ahmed\\Tyres.png". The Trim Method is used to remove the double quotes while Path.GetFileName fetches us the name of the uploaded file from which Path.GetExtension method is used to get the extension of the uploaded file from the absolute path. The next few lines combine the Server's Root Path  (by getting ApplicationBasePath property of IApplicationEnvironment ) with our provided URL, Filename & Extension of uploaded file. In between I also created a Directory in the uploads folder just to organize things nicely.
In the end always remember to use best practices like Viewmodels (Mapping Models and Viewmodels), Repositories, Exception Handling and Error Logging to make your code maintainable in the long run.


Summary:-

Here we learned ASP.NET 5's / Core's new File Handling Interface that is different from the old System.Web approach but at the same time similar enough to easily get familiar with. If you've got any questions, post'em in the comments section, I'll reply as soon as possible. Ciao!