I wrote code to upload a file in ASP.NET MVC but Server and HttpPostedFileBase are undefined in my controller.
My UploadFile.cshtml is as follows:
@{
ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
@using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.TextBox("file", "", new { type= "file"}) <br />
<input type="submit" value="Upload" />
@ViewBag.Message
</div>
}
And this is the UploadController.cs:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace WebApplication4.Controllers
{
public class UploadController : Controller
{
// GET: Upload
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult UploadFile()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
if (file is null)
{
throw new ArgumentNullException(nameof(file));
}
try
{
if (file.ContentLength > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
}
ViewBag.Message = "File Uploaded Successfully!!";
return View();
}
catch
{
ViewBag.Message = "File upload failed!!";
return View();
}
}
}
}
When I run the code, I get these errors:
The type or namespace name 'HttpPostedFileBase' could not be found (are you missing a using directive or an assembly reference?)
The name 'Server' does not exist in the current context
The best way to get path of root folder is to use
IWebHostEnviromentand for upload file type useIFormFilelike this: