Uploading File In ASP.NET(Razor)
Published on January 3, 2013
Allowing User to upload there files(eg. profile image,resume,etc..) is a very Common requirement for most of the web sites. In this article I will show you how to allow user to upload there files in asp.net websites. We will use the ASP.NET Web helpers for this task. You need to have Visual studio Express for web 2012. I recommend to use Visual studio Express for web 2012. You can download it for free of cost from //www.microsoft.com/visualstudio/eng/downloads. I am assuming you have installed Visual studio Express for web 2012. Now follow the following steps. 1)Open your VS Express For Web(go all programs search for vs express for web). 2)Create a New Web Site Under File Menu. 3)Add New Content Page(Razor v2) to website and name it as uploadfile.cshtml. 4)Right Click on your website and select Manage Nuget Packages. 5)Search with keyword helper in top right search box, from the result install ASP.NET Web Helper Library 6)Next step it will ask for Licence Acceptance, You have to click on I agree button. 7)In your uploadfile.cshtml write the following code.
@using Microsoft.Web.Helpers;
@{
Page.Title = "Title goes here";
Layout = "~/_SiteLayout.cshtml";
var msg="";
if (IsPost) {
var file = Request.Files[0];
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Server.MapPath("~/Uploads/" + fileName);
file.SaveAs(path);
msg = "Congrats! your File uploaded successfully ";
}
}
}
<!DOCTYPE html>
<html>
<head><title>File Upload Demo</title></head>
<body>
<form id="form1" method="post" enctype="multipart/form-data" action="">
<div>
<h1>File Upload Demo</h1>
@if (!IsPost) {
@FileUpload.GetHtml(allowMoreFilesToBeAdded:false)
}
<span>@msg</span>
</div>
</form>
</body>
</html>
In above code we uploading files to Uploads folder. So first we need to create Uploads folder at root of our website. In this script we want to upload only one file at a time that’s why we put allowMoreFilesToBeAdded:false by default it is true. 8)Our put of the above code is as follows.