In this article I am explaiing three ways to upload image from an ASP.NET MVC web application to server and accessing those back to display on web page. While creating a web application many times scenarios arise to upload and display an image, for example user profile image and images associated with products, articles, items or events etc. I hope this article would be helpful to implement such scenarios quickly. We will create a sample demo application using Visual Studio to understand the implementations. Following three ways to upload images are explained in this article:
Pre-requisite: You should be at intermediate level with C# and ASP.NET MVC, jQuery and HTML to have a good time with this article. For beginners, Please learn the basics of above technologies first and you can put comments below article in case of any query. I will be happy to answer your queries. Thanks.
Acknowledgments: While writing this article, I have taken help of few blogs and used libraries written by other respected programmers. I have mentioned links to those blogs and libraries in "References" section of this article. Huge thanks to those authors and programmers.
To provide a quick idea of what we would be accomplishing at the end of code demo of this article, below is the screenshot of finished application having links to all three demos:
YouTube Video: Many thanks to sashkhdr for sharing a video based on this article on youtube here. It is having live demo describing the functionality of application which we will be creating in this article. Thanks.
Let us get started by creating a demo application.
Before starting, please note the following points while following the steps given to creating demo applications:
Now lets fire up Visual Studio and start building demo:
<head> <meta charset="utf-8" /> <title>@ViewBag.Title - My ASP.NET MVC Application</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width" /> <script src="~/Scripts/jquery-1.8.2.min.js"></script> @*Referenced appcss file having custom CSS*@ <link href="~/Content/custom/appcss.css" rel="stylesheet" /></head>
<body><div class="navigationPanel"> <div style="margin: 40px 25px 2px 25px;"> <span style="color:green;font-weight:bolder; font-size:large">Links to Demostrations</span> <br /> <br /> <span style="color: #CC3300; font-weight: bold; font-style: italic">Uploading Image by</span> <br /> <br /> <a href="~/Home/GetPVforFileBrowsing">Browsing File</a> <br /> <br /> <a href="~/Home/GetPVDragDropUsingjQuery">Dragging and Dropping</a> <br /> <br /> <a href="~/Home/GetPVUsingWebCam">Capturing using Webcam</a> <br /> <br /> </div> </div> <div style="float: left; margin: 25px 2px 2px 80px;"> @RenderBody()</div></body>
public class ImageModel{ public string ImageName { get; set; } public string ImagePath { get; set; }}
So far, we have created common code which we will be using in all three demos. Further, we will learn each scenario one by one.
public ActionResult GetPVforFileBrowsing(){ return View();}
<h3>Uploading Image by Browsing File:</h3><table> <tr> <td> <span>Image Name</span> </td> <td> <input type="text" id="txtImageName" /> </td> <td> <div id="validateImageInput" class="warrningMessage">Please enter image name</div> </td> </tr> <tr> <td> <br /> <span>Upload Image</span> </td> <td> <br /> <input type="file" id="selectedImage" name="image" /> </td> <td> <br /> <div id="validateSelectedImage" class="warrningMessage">Please browse image file</div> </td> </tr> <tr> <td> <br /> <input type="button" id="btnBrowsedSave" value="Save Borwsed Image" /> </td> <td> <br /> <input type="button" id="btnViewImage" value="View Saved Image" /> </td> </tr></table><br /><br />@*Container of ViewSavedImage partial view*@<div id="pvContainerDiv"></div><script src="~/Scripts/Js/file-browsing.js"></script>
$(document).ready(function (){ $("#btnViewImage").hide(); $("#validateImageInput ").hide(); $("#validateSelectedImage").hide();});$("#txtImageName").keydown(function () { $("#validateImageInput").hide();});$("#selectedImage").click(function () { $("#validateSelectedImage").hide();});$("#btnBrowsedSave").click(function () { var imageName = $("#txtImageName").val(); var formData = new FormData(); var totalFiles = document.getElementById("selectedImage").files.length; var browsedFile = document.getElementById("selectedImage").files[0]; if (imageName == "") $("#validateImageInput").show(); if (totalFiles == 0) $("#validateSelectedImage").show() if ((imageName != "") && (totalFiles != 0)) { if (browsedFile.type.match('image.*')) { formData.append("FileUpload", browsedFile); formData.append("ImageName", imageName); $.ajax({ type: "POST", url: '/Home/UploadImage', data: formData, dataType: "html", contentType: false, processData: false, success: function (result) { $("#btnViewImage").show(); } }); } else { alert("Please browse image file only."); } }});In above code, first, we are hiding “View Saved Image” button which would be visible when user click on “Save Captured Image” button to see just uploaded image and two div which are having text used for validation purpose. Using Ajax request we are sending uploaded image to UploadImage action method in controller.
[HttpPost]public void UploadImage(){ foreach (string upload in Request.Files) { string path = AppDomain.CurrentDomain.BaseDirectory + "ImagesUploaded/"; string filename = Path.GetFileName(Request.Files[upload].FileName); Request.Files[upload].SaveAs(Path.Combine(path, filename)); imageModel.ImagePath = filename; imageModel.ImageName = Request.Form["ImageName"]; }}
@model ImageUploadDemo.Models.ImageModel<div id="viewSavedContentAreaDiv"> <h4>This is your recently uploaded image details:</h4> <table> <tr> <td class="pvTdFirst"> <span>Image Name</span> </td> <td class="pvTdSecond"> <span>@Model.ImageName</span> </td> </tr> <tr> <td class="pvTdFirst"><br /> <span>Uploaded Image</span> </td> <td class="pvTdSecond"><br /> <div > <img class="viewSavedImage" src="@Url.Content(String.Format("~/ImagesUploaded/{0}", Model.ImagePath))"> </div> </td> </tr> </table></div>
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]public ActionResult ViewSavedImage(){ return PartialView("ViewSavedImage", imageModel);}Here we are using OutputCache attribute and setting some properties: NoStore = true (No cache will be maintained); Duration = 0 (cache duration would be zero) and VaryByParam = "*" (can vary by any parameters) is used. We do not want the output of this action method to be cached at all bacause it should aways return the latest uploaded image.
$("#btnViewImage").click(function () {$.ajax({ type: "Get", url: '/Home/ViewSavedImage', dataType: "html", contentType: false, processData: false, success: function (result) { $("#pvContainerDiv").empty().append(result); }});});
public ActionResult GetPVDragDrop(){ return View();}
$(document).ready(function () { $("#btnViewImage").hide(); $("#validateImageInput ").hide(); $("#validateDroppedImage").hide();});var dropArea = $("#dropAreaDiv");var newFile;// Providing handlers three events to the drop areadropArea.on({ "drop": makeDrop, "dragenter": ignoreDrag, "dragover": ignoreDrag});//Stop default behavior function ignoreDrag(e) { e.stopPropagation(); e.preventDefault();}//Handling drop eventfunction makeDrop(e) { var fileList = e.originalEvent.dataTransfer.files, fileReader; e.stopPropagation(); e.preventDefault(); if (fileList.length > 0) { newFile = fileList[0]; if (newFile.type.match('image.*')) { $("#validateDroppedImage").hide(); fileReader = new FileReader(); fileReader.onloadend = handleReaderOnLoadEnd($("<img />")); fileReader.readAsDataURL(fileList[0]); } else { alert("Please select an image file only."); } }}//Setting the image sourcefunction handleReaderOnLoadEnd($image) { return function (event) { $image.attr("src", this.result) .addClass("small") .appendTo("#dropAreaDiv"); };}$("#txtImageName").keydown(function () { $("#validateImageInput").hide();});$("#btnDroppedSave").click(function () { var imageName = $("#txtImageName").val(); if (imageName == "") $("#validateImageInput").show(); var imgSource = $("#dropAreaDiv").find("img").attr("src"); if (imgSource == undefined) $("#validateDroppedImage").show(); if ((imageName != "") && (imgSource != undefined)) { var formData = new FormData(); var totalFiles = 1; var dropedFile = newFile; formData.append("FileUpload", dropedFile); formData.append("ImageName", imageName); $.ajax({ type: "POST", url: '/Home/UploadImage', data: formData, dataType: "html", contentType: false, processData: false, success: function (result) { $("#btnViewImage").show(); } }); }});$("#btnViewImage").click(function () { $.ajax({ type: "Get", url: '/Home/ViewSavedImage', dataType: "html", contentType: false, processData: false, success: function (result) { $("#pvContainerDiv").empty().append(result); } });});In above ajax call, we are targeting to UploadImage action method which is same method which we have used in above demo for saving image by browsing image file.
In this scenario, we will capture image from systems’s webcam so in your system webcam must be enabled. I have used a plugin which is written in jQuery and swf file which is written in adobe flash action Script. This plugin is written by Robert Eisele please find links to his blog in the Reference section of this article. I have kept those two files in ExternalJs folder of the application.
public ActionResult GetPVUsingWebCam (){ return View();}
$(document).ready(function () { $("#btnViewImage").hide(); $("#validateImageInput").hide(); $("#validateCameraInput").hide(); // assigning properties and adding callback fuctions $("#cameraArea").webcam({ width: 250, height: 160, mode: "save", swffile: "/Scripts/ExternalJs/jscam.swf", onTick: function () { }, onSave: function () { }, onCapture: function () { var imageName = $("#txtImageName").val(); var url = getContextPath() + "CameraCapture/" + imageName; webcam.save(url); $("#btnViewImage").show(); }, debug: function (type, message) { if (message === "Camera started") { window.webcam.started = true; } }, onLoad: function () { } }); // Validating and calling capture method of webcam $("#btnCaptureSave").click(function () { var imageName = $("#txtImageName").val(); if (imageName === "") { $("#validateImageInput").show(); } else { $("#validateImageInput").hide(); if (!webcam.started) { $("#validateCameraInput").show(); } else { $("#validateCameraInput").hide(); $("#btnViewImage").hide(); webcam.capture(); } } }); function getContextPath() { var ctx = window.location.pathname, path = '/' !== ctx ? ctx.substring(0, ctx.indexOf('/', 1) + 1) : ctx; return path + (/\/$/.test(path) ? '' : '/'); } $("#txtImageName").keydown(function () { $("#validateImageInput").hide(); }); $("#btnViewImage").click(function () { $.ajax({ type: "Get", url: '/Home/ViewSavedImage', dataType: "html", contentType: false, processData: false, success: function (result) { $("#pvContainerDiv").empty().append(result); } }); });});In above ajax call, we are targeting CameraCapture action method to save the image.
In this article we learned three ways to save the image in ASP.NET MVC application: by browsing file, by dragging and dropping and by taking snap using webcam. I tried to keep code as simple as possible so that it could be easy to understand and reusable. Your comments and suggestions are most welcome with detail to improve the article. Thanks for reading.
联系客服