Uploading Image With ASP.NET(Razor-WebImage)
Published on January 14, 2013
In Uploading File In ASP.NET(Razor) post i explained how to upload file in asp.net. File means any thing even image file also. Today’s post i will explain how to upload images in ASP.NET web app. But this time instead of using FileUpload helper. We will use WebImage helper. You may think why WebImage? WebImage is a special helper to manipulate Images on Web. We can do different operations like flipping, cropping, re-sizing, watermarking,etc.. with this WebImage helper. I will write how to do these operations in later posts. In today’s post we will only focus on how to upload an image in ASP.NET with the help of web image helper.
You need to install Visual studio Express for web 2012 for this post. You can download it for free 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 uploadimage.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)Now open your uploadimage.cshtml and copy past the following code.
@{
Page.Title = "Image Upload using WebImage Helper";
Layout = "~/_SiteLayout.cshtml";
var path = "";
if (IsPost)
{
WebImage photo = WebImage.GetImageFromRequest();
if (photo != null)
{
var imgname =Path.GetFileName(photo.FileName);
path = @"Uploads\" + imgname;
photo.Save(@"~\" + path);
}
}
}
<div>
<h1>Upload Image</h1>
<form action="" method="post" enctype="multipart/form-data">
<fieldset>
<legend> Upload Image </legend>
<label for="Image">Image</label>
<input type="file" name="Image" />
<br/>
<input type="submit" value="Submit" />
</fieldset>
</form>
@if(path != ""){
<div class="result">
<img src="@path" alt="Thumbnail image" />
</div>
}
</div>