MVC 4 Razor File Upload
The Upload
method's HttpPostedFileBase
parameter must have the same name as the the file input
.
So just change the input to this:
<input type="file" name="file" />
Also, you could find the files in Request.Files
:
[HttpPost]
public ActionResult Upload()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("UploadDocument");
}
Clarifying it. Model:
public class ContactUsModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public HttpPostedFileBase attachment { get; set; }
Post Action
public virtual ActionResult ContactUs(ContactUsModel Model)
{
if (Model.attachment.HasFile())
{
//save the file
//Send it as an attachment
Attachment messageAttachment = new Attachment(Model.attachment.InputStream, Model.attachment.FileName);
}
}
Finally the Extension method for checking the hasFile
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AtlanticCMS.Web.Common
{
public static class ExtensionMethods
{
public static bool HasFile(this HttpPostedFileBase file)
{
return file != null && file.ContentLength > 0;
}
}
}