In this tutorial, we will learn how to create an ASP.NET MVC project that allows users to upload files or images and store them in the program. We will cover the model, controller, and view components required for this functionality.
#Model
First, let's create a model class that will define the properties of our file upload form. Create a new class called FileUploadModel.cs in your project's Models folder and add the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace test.Models
{
public class FileUploadModel
{
[DataType(DataType.Upload)]
[Display(Name = "Upload File")]
[Required(ErrorMessage = "Please choose a file to upload.")]
public string file { get; set; }
}
}
In this model, we have a property called file of type string. We have applied data annotations such as DataType.Upload, Display, and Required to define the behavior and validation rules for the file upload field.
#Controller
Next, let's create a controller that will handle the file upload functionality. Open your project's HomeController.cs file (or create a new controller) and add the following code:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFiles(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
try
{
if (file != null)
{
string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.FileStatus = "File uploaded successfully.";
}
catch (Exception)
{
ViewBag.FileStatus = "Error while uploading the file.";
}
}
return View("Index");
}
In this controller, we have two action methods. The Index action method returns the view for the file upload form. The UploadFiles action method is decorated with the [HttpPost] attribute to handle the form submission.
Inside the UploadFiles action method, we first check if the model state is valid. If it is, we retrieve the uploaded file using the HttpPostedFileBase parameter. We then check if the file is not null and save it to a specified path on the server.
Finally, we set the ViewBag.FileStatus property to indicate the status of the file upload process.
#View
Now, let's create the view that will render the file upload form. Create a new view called Index.cshtml (or modify an existing view) and add the following code:
@model test.Models.FileUploadModel
@{
ViewBag.Title = "www.compilemode.com";
}
@using (Html.BeginForm("UploadFiles", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type = "file" } })
@Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Upload" class="btn btn-primary" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-success">
@ViewBag.FileStatus
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
In this view, we first specify the model type at the top using the @model directive. We then create a form using the Html.BeginForm helper method, specifying the action and controller names for the form submission.
Inside the form, we have a file upload field generated by the EditorFor helper method, which is bound to the file property of the model. We also display any validation errors using the ValidationMessageFor helper method.
Finally, we display the file upload status using the ViewBag.FileStatus property, which we set in the controller.
Summary
In this tutorial,we learned how to create a file upload project in ASP.NET MVC. We created a model class to define the file upload form, a controller to handle the file upload functionality, and a view to render the file upload form and display the upload status.
By following the steps outlined in this tutorial, you can enable users to upload files or images to your ASP.NET MVC application and store them for further processing or display. Remember to handle file validation and implement appropriate security measures when working with user-uploaded files.
I hope this tutorial has been helpful in understanding the process of creating a file upload project in ASP.NET MVC. Happy coding!
Resource: https://www.compilemode.com/2018/02/upload-images-on-server-folder-in-asp-net-mvc.html