Upload File MVC

.Net4.x MVC

Upload and save some file.

FileUploadViewModel

1
2
3
4
public string Foo { get; set; }

[Display(Name = "Some File")]
public List<HttpPostedFileBase> Files { get; set; }

FileUploadController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SomeAction([Bind(Include = "Foo,Files")] FileUploadViewModel vwModel)
{
if (vwModel.Files[0] != null)
{
var fileSize = vwModel.Files[0].InputStream.Length;
var limit = Convert.ToInt64(ConfigurationManager.AppSettings["allowedUploadFilesSize"]);
if (fileSize > limit)
{
// moan with message that converts `limit` from bytes to string.
// 10485760 is 10mb as bytes
}

HttpPostedFileBase postedFile = vwModel.Files[0];
var fi = new FileInfo(postedFile.FileName);
var saveName = $("{Guid.NewGuid()}{fi.Extension}");
var savePath = $("{AppDomain.CurrentDomain.BaseDirectory}{saveName}");
postedFile.SaveAs(savePath);

View FileUpload.cshtml

1
2
3
4
5
@using (Html.BeginForm("SomeAction", "FileUpload", FormMethod.Post, new { encType = "multipart/form-data", id = "uploadForm" }))
{
// wrapper divs and magic here
@Html.LabelFor(model => model.Files, htmlAttributes: new { @class = "control-label" })
@Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files", @class = "form-control", @onchange = "Save();" })

Client side post-back after the file changes is triggered by @onchange

1
2
3
4
function Save() {
Loading();
document.getElementById('uploadForm').submit();
}