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!

23 comments:

  1. I think it is very early to make dotnetcore publicly available as you cant carry out most of the basic tasks a dev typically would want to do. Also I am curious how often a dev changes an ORM to require a repository pattern? Especially if the reason is to show a sample code like this.

    ReplyDelete
    Replies
    1. Regarding .NET Core, yes it's not yet ready for production, no matter what Microsoft says. And as for the Repository Pattern, a typical scenario for changing ORM would be if you want to jump onto NoSQL bandwagon. Btw, you can easily substitute Repository Function calls with Entity Framework Function Calls. Hope this helps. Cheers.

      Delete
  2. Hi, I've followed your tutorial and faced some issues.
    I wrote the issue on StackOverflow
    http://stackoverflow.com/questions/40447338/adding-images-to-asp-net-core

    ReplyDelete
    Replies
    1. Hey it seems you need to learn basics of web development using MVC frameworks in general. I can teach you via skype if you need help. But please avoid posting these kind of general / noob(ish) questions on stackoverflow. And first learn the basics and then jump onto advance topics like these. Hope this helps.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Fileextesnions attribute only works with string type.

    ReplyDelete
  5. I am really happy with your blog because your article is very unique and powerful for new reader.
    selenium training in chennai

    ReplyDelete
  6. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    iot-training-in-chennai


    ReplyDelete
  7. Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.
    python training in velachery
    python training institute in chennai

    ReplyDelete
  8. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram
    DevOps online Training

    ReplyDelete
  9. Your story is truly inspirational and I have learned a lot from your blog. Much appreciated.
    Blueprism training in velachery

    Blueprism training in marathahalli

    ReplyDelete

  10. Thanks for sharing the knowledgeable stuff to enlighten us no words for this amazing blog.. learnt so many things I recommend everyone to learn something from this blogger and blog.. I am sharing it with others also
    IT Software Training in Chennai | Python Training in Chennai | Dot Net Training in Chennai |Android Training in Chennai

    ReplyDelete
  11. Title:
    Best Oracle Training in Chennai | Infycle Technologies

    Description:

    If Oracle is a job that you're dreaming of, then we, Infycle are with you to make your dream into reality. Infycle Technologies offers the best Oracle Training in Chennai, with various levels of Oracle courses such as Oracle PLSQL, Oracle DBA, etc., in 100% hands-on practical training with professional tutors in the field. Along with that, the mock interviews will be done for the candidates, so that, they can face the interviews with full confidence.
    Best traiing in Chennai

    ReplyDelete
  12. Description:
    Infycle Technologies is the best software training center in Chennai, providing amazing Data Science training in Chennai which will be realistic and taught by industry experts. Aside from practical training preparation, mock interviews will be arranged for students so that they can confidently face the interviews. All of this will be packed up by full placement assurance with the best salary package from top companies. For having a free demo session, call 7502633633.
    best training institute in chennai

    ReplyDelete
  13. Smart move for your career is Choosing to do Oracle Course in Chennai at Infycle!! Do you know why this name is chosen for Infycle. Infycle where the place we offered Infinity of Oracle.
    Yes!!! But not only Oracle, More than 20+ courses are offered here 5000+ students are placed in top MNC’s Company with good salary packages. For admission 7502633633 Oracle Course in Chennai | Infycle Technologies

    ReplyDelete
  14. Pull- up your socks and knot your tie. Gonna have a good salary package job after completing Big-data H adoop training in Chennai at Infycle. Infylce is completely for Software training and placement by friendly trainees, good atmosphere, 200% practical classes, and more.

    ReplyDelete
  15. Harrah's Cherokee Casino & Hotel - MapYRO
    Welcome to Harrah's 서산 출장샵 Cherokee Casino 구리 출장마사지 & Hotel, where fun is always fun. The location is convenient to Murphy at 포항 출장안마 Cherokee Casino 천안 출장샵 Parkway and 사천 출장샵 Murphy at

    ReplyDelete