-
Notifications
You must be signed in to change notification settings - Fork 0
15 Upload Files
M. Fares edited this page Mar 15, 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.
-
Create a folder in the content directory where the files are to be saved/uploaded
/Content/Uploads -
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; }
}- 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; }
}- 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
// POST: Course/Create
[HttpPost]
public ActionResult Create(CourseViewModel model)
{
if (ModelState.IsValid)
{
// Create the course from the model
var course = new Course
{
Code = model.Code,
Title = model.Title,
Description = model.Description
};
//TODO Remove invalid characters from the filename such as white spaces
// check if the uplaoded file is empty (do not upload empty files)
if (model.Outline.ContentLength > 0)
{
// Allowed extensions to be uploaded
var extensions = new List<string> { ".pdf", ".docx", ".doc" };
// using System.IO for Path class
// Get the file name without the path
string filename = Path.GetFileName(model.Outline.FileName);
// Get the extension of the file
string ext = Path.GetExtension(filename);
// Check if the extension of the file is in the list of allowed extensions
if (extensions.Contains(ext, StringComparer.OrdinalIgnoreCase))
{
// Set the application folder where to save the uploaded file
string appFolder = "~/Content/Uploads/";
// Generate a random string to add to the file name
// This is to avoid the files with the same names
var rand = Guid.NewGuid().ToString();
// Combine the application folder location with the file name
string path = Path.Combine(Server.MapPath(appFolder), rand + "-" + filename);
// Save the file in ~/Content/Uploads/filename.xyz
model.Outline.SaveAs(path);
// Add the path to the course object
course.OutlineFilePath = appFolder + rand + "-" + filename;
}
}
// Save the created course to the database
db.Courses.Add(course);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View();
}
}- Create a view with the appropriate parameters of the Html.BeginForm(...) and an input tag of type file.
Example: /Views/Course/Create.cshtml
@model SchoolWebApp.ViewModels.CourseViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Course", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Course</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Code, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Code, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Code, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<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>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}- 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.
- To test this feature go to /Course/Create