Simple MVC3/Razor Fileupload and Storage
Recently I had to add a simple fileupload control in an MVC3 Razor page. It wasn't very difficult to do, thanks to System.Web.Helpers and Microsoft.Web.Helpers.
- To begin... if you don't have Microsoft.Web.Helpers, find and install through NuGet.
- Next in your Razor view add the following :
@using Microsoft.Web.Helpers
@{
ViewBag.Title = "Upload Files";
}
@using (Html.BeginForm("Upload","Upload", FormMethod.Post, new { @encType = "multipart/form-data" }))
{
@FileUpload.GetHtml(initialNumberOfFiles:1, allowMoreFilesToBeAdded:true, includeFormTag:false, addText:"Add Files", uploadText: "Upload File") | |
< input type="submit" name="submit" text="upload" /> } |
- Next in your Upload Controller add the following. The submit button on the Razor page submits the form to the Upload action in Upload Controller. HttpPostedFileBase is a System.Web class that provides access to individual files that are uploaded by the client.
- We loop through the files and save them to the App_Data/uploads folder.
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
public class UploadController : Controller
{
public ActionResult Index()
{
return View("Index");
}
public ActionResult Upload(IEnumerable fileupload)
{
if (fileupload.Count() > 0)
{
foreach (var fileBase in fileupload)
{
var fileName = Path.GetFileName((fileBase.FileName));
if (fileName != null)
{
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
fileBase.SaveAs(path);
}
}
}
return RedirectToAction("Index");
}
}
You can also consider using a drag and drop uploader using jquery, like http://aquantum-demo.appspot.com/file-upload . It has the limitation that it won't support IE, or older versions of other browsers.
ReplyDeleteJust a note for other readers, when I entered the package manager command it installed a version of Microsoft.Web.Helpers which broke my existing solution as it used new dll versions which conflicted with existing dll references. The workaround was to use the below package manager command instead:
ReplyDeleteInstall-Package microsoft-web-helpers -Version 1.15
ReplyDeleteThe Article on Mobile testing Services Map is awesome nice pie chart description, thanks for sharing the information about it.Mobile app testing companies and load testing services.