File Download Sample in MVC: Day 40

Let's see the 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. Create an Images folder and add some images inside that for the download.

    image

  5. Create an action method, "Download".

  6. To add a view, right-click on "Download" and select "Add View...".

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

  8. In Download.cshtml we get the list of images in the Model. We create an individual action link by iterating the model for all the images. In the actionlink we specify "DownloadFile" as the action method.

    code

  9. Here we create two action methods. One is to get the list of images and another one is to download the file. In the Download action result we get the list of files using DirectoryInfo and FileInfo. The DownloadFile action result returns the FilePathResult with filename and content type.

    c sharp code

  10. Now run the project and you can see all the images with download link.

    local host

  11. Click on any of the images and you have an option to save the image. Press the "OK" button to save the image.

    download file


Similar Articles