Skip to content

15 Upload Files

M. Fares edited this page Mar 22, 2018 · 10 revisions

This page demonstrates how to upload files to your application, store them in a folder under your app, and save the file path in the database.

  1. Create a folder in the content directory where the files are to be saved/uploaded
    /Content/Uploads

  2. The domain class should have a property where to store the path to the uploaded file
    Example: /Models/Course.cs

public class Course
{
    ...
    public string OutlineFilePath { get; set; }
}
  1. Create the view model class with the properties
    Example: /ViewModels/CourseViewModel.cs
public class CourseViewModel
{
    // The outline file as object (used to upload a file)
    [Display(Name ="Outline File")]
    public HttpPostedFileBase Outline { get; set; }

    // The outline file path as string (used to diplay the path)
    public string OutlineFilePath { get; set; }
}
  1. Implement the controller action that receives the uploaded file and save the file in the application folder.
    Example: See Create action in /Controllers/CourseController.cs

  2. Create a view with the appropriate parameters of the Html.BeginForm(...) and an input tag of type file.
    Example: /Views/Course/Create.cshtml

<div class="form-group">
 @Html.LabelFor(model => model.Outline, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
       @Html.TextBox("Outline", "", new { type = "file" })
   </div>
</div>

The first parameter of the @Html.TextBox (i.e. Outline) has to match the property name in your view model (i.e. CourseViewModel) 6. Check the uploaded
The files are stored in the folder /Content/Uploads. To see these files, right-click on this folder in the Solution Explorer (Visual Studio) and select "Open Folder in File Explorer".

The paths to these files are stored in the Course table. To see them, select view data in SQL Object Explorer.

  1. To test this feature go to /Course/Create

Clone this wiki locally