File Upload Sample in MVC: Day 38

In this article we will see how to upload a file in MVC and save it in the application root directory.

Let's see the following step-by-step implementation:

  1. Create an MVC project from the "Empty" template.

    Right-click on "Controllers" and select "Add" >> "Controller...".

  2. Select "MVC 5 Controller - Empty" to add an empty controller.

    Click on the "Add" button.

  3. Name the controller "HomeController".

    The Index() action result method will be added.

  4. To add a view, right-click on "Index" and select "Add View...".

  5. Name the view and select "Empty (without model)" as the template. Click on the "Add" button.

  6. We use the form attribute with the post method in our cshtml file. We use enctype as "multipart/form-data". This attribute specifies how the form data should be encoded when uploading it to the server. By default its value is "application/x-www-form-urencoded"; that means that all the characters are encoded before being sent. Here we use "multipart/form-data" that is used when we have a file upload control because it does not encode any value. There is one more value that you can use, "text/plain" that does not encode any special character. This is all about the form attribute. Inside the form attribute we have created a file upload control and submit button.

    created file upload control and submit button

  7. Once a file is posted, it will be available as an HttpPostedFileBase parameter. HttpPostedFileBase serves as the base class for classes that provide access to individual files that have been uploaded by the client. Using HttpPostedFileBase we can have properties like ContentLength, ContentType, FileName and so on. First we get the physical path of our application using Server.MapPath and then save the file inside the images folder.

    controller

  8. Now run the project and click on the "Choose File" button, select the file that you want to upload from your directory structure and press the "Upload" button.

    file upload

  9. The file is uploaded to the server and we can also see it in the browser.

    file is uploaded to the server
  10. We can also check for the existence of this file in the images folder.

    file in the images folder


Similar Articles