Source : https://www.compilemode.com/2018/02/upload-images-on-server-folder-in-asp-net-mvc.html
public class FileUploadModel
{
[DataType(DataType.Upload)]
[Display(Name = "Upload File")]
[Required(ErrorMessage = "Please choose file to upload.")]
public string file { get; set; }
}
public class FileUploadController : Controller
{
// GET: FileUpload
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFiles(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
try
{
//Method 2 Get file details from HttpPostedFileBase class
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 file uploading."; ;
}
}
return View("Index");
}
}
Index.cshtml
@model ImageUploadMVC.Models.FileUploadModel
@{
ViewBag.Title = "www.com";
}
@using (Html.BeginForm("UploadFiles", "FileUpload", 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>
CREATE a folder : UploadedFiles
0 Comments