<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Upload in MVC &#8211; Sibeesh Passion</title>
	<atom:link href="https://www.sibeeshpassion.com/tag/upload-in-mvc/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:20:02 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Upload in MVC &#8211; Sibeesh Passion</title>
	<link>https://www.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Upload Files To Azure Media Service From Server Side In MVC</title>
		<link>https://www.sibeeshpassion.com/upload-files-to-azure-media-service-from-server-side-in-mvc/</link>
					<comments>https://www.sibeeshpassion.com/upload-files-to-azure-media-service-from-server-side-in-mvc/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 30 Jun 2016 12:06:57 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[File Uploading Using MVC]]></category>
		<category><![CDATA[Upload Files To Azure Media Service]]></category>
		<category><![CDATA[Upload in MVC]]></category>
		<category><![CDATA[Uploading image to the assets]]></category>
		<category><![CDATA[Using ImageResizer]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11744</guid>

					<description><![CDATA[In this article we are going to see how we can upload images or any files to Media Service Account in Azure from the server side. We will be doing the uploading in a MVC application. If you are new to Azure media service account, I strongly recommend you to read my previous post related to media service account. In my previous article we saw how we can Upload Images To Azure Media Service From Client Side. Here we will see how we can do the same process from the server side. We will also see how we can create [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we are going to see how we can upload images or any files to Media Service Account in <a href="http://sibeeshpassion.com/category/Azure/" target="_blank">Azure</a> from the server side. We will be doing the uploading in a <a href="http://sibeeshpassion.com/category/mvc/" target="_blank">MVC </a>application. If you are new to Azure media service account, I strongly recommend you to read my previous post related to <a href="http://sibeeshpassion.com/working-with-azure-media-service-account/" target="_blank">media service account</a>. In my previous article we saw how we can <a href="http://sibeeshpassion.com/upload-images-to-azure-media-service-from-client-side/" target="_blank">Upload Images To Azure Media Service From Client Side</a>. Here we will see how we can do the same process from the server side. We will also see how we can create thumbnails for the image you upload, once we generated it, we will upload that to media service account. I hope you will like this.</p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/Upload-Files-To-Azure-7ad7d20f" target="_blank">Upload Files To Azure Media Service</a></p>
<p><strong>Background</strong></p>
<p>For the past few weeks I am working in <a href="http://sibeeshpassion.com/category/Azure/" target="_blank">Azure </a>. Recently I got a requirement of storing images to Azure. Thus I decided to create a media service account for this requirement. I hope you have already saw my previous articles related to Media Services, if not please find those from here: <a href="http://sibeeshpassion.com/category/azure/media-service/" target="_blank">Media Service</a>. </p>
<p>Now I assume that you have a little background of below items.</p>
<li>Azure media service account</li>
<li>Assets in media service account</li>
<li>Blobs in media service account</li>
<p>Shall we start now?</p>
<p><strong>Prerequisites</strong></p>
<li>Visual Studio</li>
<li>Azure account with active subscription</li>
<li>Active media service, associated storage account account and its keys</li>
<li>ImageResizer DLL for generating the resized stream</li>
<p>If you are a start up company or you are in thinking to start a one, you can always go for BizSpark(Software and services made for the start ups), to join please check here: <a href="http://sibeeshpassion.com/how-to-join-bizspark/" target="_blank">How to join bizspark</a>. Or you can always create a free account <a href="https://azure.microsoft.com/en-in/pricing/free-trial/" target="_blank">here</a>.</p>
<p><strong>Things we are going to do</strong></p>
<p>The following are the tasks we are going to do.</p>
<li>Creating a MVC application.</li>
<li>Create an Asset in Media service account</li>
<li>Upload the file to asset created dynamically</li>
<li>Resize the stream with help of ImageResizer and upload</li>
<li>Retrieves the uploaded items</li>
<p>Now we will go and create a MVC application.</p>
<p><strong>Create a MVC application</strong></p>
<p>Click on the File->New->Project and name your project, in the upcoming window please select MVC and create your project. Once your project is loaded, you can create a MVC controller as follows.</p>
<p>[csharp]<br />
 public class HomeController : Controller<br />
    {<br />
        public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
    }<br />
[/csharp]</p>
<p>And create a view as follows.</p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Home Page&quot;;<br />
}</p>
<p>&lt;div class=&quot;jumbotron&quot;&gt;<br />
    &lt;h1&gt;Sibeesh Venu&lt;/h1&gt;<br />
    &lt;p class=&quot;lead&quot;&gt;Welcome to Sibeesh Passion&#8217;s Azure Media Service Library&lt;/p&gt;<br />
    &lt;p&gt;&lt;a href=&quot;http://sibeeshpassion.com&quot; class=&quot;btn btn-primary btn-lg&quot;&gt;Learn more &amp;raquo;&lt;/a&gt;&lt;/p&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>Now we need to create an another action in the controller and view for upload. Shall we?</p>
<p>[csharp]<br />
 public ActionResult Upload()<br />
        {<br />
            return View();<br />
        }<br />
[/csharp]</p>
<p>And create a view as follows.</p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Upload&quot;;<br />
}</p>
<p>&lt;h2&gt;Upload&lt;/h2&gt;<br />
&lt;style&gt;<br />
    table, td, tr {<br />
        border: 1px solid #ccc;<br />
        border-radius: 5px;<br />
        padding: 10px;<br />
        margin: 10px;<br />
    }</p>
<p>    span {<br />
        padding: 10px;<br />
        margin: 10px;<br />
    }<br />
&lt;/style&gt;<br />
&lt;input name=&quot;myFile&quot; id=&quot;myFile&quot; type=&quot;file&quot; multiple /&gt;&lt;br/&gt;<br />
&lt;input type=&quot;button&quot; value=&quot;Submit&quot; id=&quot;btnSubmit&quot; class=&quot;btn btn-info&quot; /&gt;<br />
&lt;div id=&quot;fiesInfo&quot;&gt;&lt;/div&gt;<br />
&lt;div id=&quot;divOutput&quot;&gt;&lt;/div&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/Upload.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Here <em>Upload.js</em> is the file where our client side codes relies. So shall we create the client side functions related to the upload process?</p>
<p>[js]<br />
  $(&#8216;#btnSubmit&#8217;).click(function () {<br />
        $(&#8216;#fiesInfo&#8217;).html(&#8221;);<br />
        $(&#8216;#divOutput&#8217;).html(&#8221;);<br />
        startDateTime = new Date();<br />
        $(&#8216;#fiesInfo&#8217;).append(&#8216;&lt;br/&gt;&lt;br/&gt;&lt;span&gt;&lt;b&gt;Uploading starts at&lt;/b&gt;&lt;/span&gt;&#8217; + startDateTime);<br />
        var data = new FormData();<br />
        var files = $(&quot;#myFile&quot;).get(0).files;<br />
        if (files.length &gt; 0) {<br />
            for (var i = 0; i &lt; files.length; i++) {<br />
                data.append(&quot;UploadedImage_&quot; + i, files[i]);<br />
            }<br />
            var ajaxRequest = $.ajax({<br />
                type: &quot;POST&quot;,<br />
                url: &quot;http://localhost:5022/Home/UploadFile&quot;,<br />
                contentType: false,<br />
                processData: false,<br />
                data: data,<br />
                cache: false,<br />
                success: function (data, status) {<br />
                    debugger;<br />
                    var totSize = 0;<br />
                    $(&#8216;#divOutput&#8217;).hide();<br />
                    $(&#8216;#fiesInfo&#8217;).append(&#8216;&lt;table&gt;&lt;/table&gt;&#8217;);<br />
                    for (var i = 0; i &lt; data.length; i++) {<br />
                        totSize = totSize + parseFloat(data[i].ImageSize);<br />
                        $(&#8216;#divOutput&#8217;).append(&#8216;&lt;img style=&quot;float: left;padding:10px;margin:5px;&quot;  src=https://&#8217; + mediaServiceAccount + &#8216;.blob.core.windows.net/&#8217; + data[i].AssetID + &#8216;/&#8217; + data[i].Title + &#8216; /&gt;&#8217;);<br />
                    }<br />
                    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;No of files uploaded: &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + data.length + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
                    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;Total size uploaded: &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + formatSizeUnits(totSize) + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
                    var endDateTime = new Date();<br />
                    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;Uploading ends at &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + endDateTime + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
                    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;The time taken is &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + findDateDiff(startDateTime, endDateTime) + &#8216; &lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
                    $(&#8216;#divOutput&#8217;).show();<br />
                },<br />
                error: function (xhr, desc, err) {<br />
                    $(&#8216;#divOutput&#8217;).html(&#8216;Error: &#8216; + err);<br />
                }<br />
            });<br />
        }</p>
<p>    });<br />
[/js]</p>
<p><em>findDateDiff(date1, date2)</em></p>
<p>[js]<br />
  function findDateDiff(date1, date2) {<br />
        //Get 1 day in milliseconds<br />
        var one_day = 1000 * 60 * 60 * 24;</p>
<p>        // Convert both dates to milliseconds<br />
        var date1_ms = date1.getTime();<br />
        var date2_ms = date2.getTime();</p>
<p>        // Calculate the difference in milliseconds<br />
        var difference_ms = date2_ms &#8211; date1_ms;<br />
        //take out milliseconds<br />
        difference_ms = difference_ms / 1000;<br />
        var seconds = Math.floor(difference_ms % 60);<br />
        difference_ms = difference_ms / 60;<br />
        var minutes = Math.floor(difference_ms % 60);<br />
        difference_ms = difference_ms / 60;</p>
<p>        //var hours = Math.floor(difference_ms % 24);<br />
        //var days = Math.floor(difference_ms / 24);</p>
<p>        return minutes + &#8216; minute (s), and &#8216; + seconds + &#8216; second (s)&#8217;;<br />
    };<br />
[/js]</p>
<p><em>formatSizeUnits(bytes)</em></p>
<p>[js]<br />
     function formatSizeUnits(bytes) {<br />
        if (bytes &gt;= 1000000000) { bytes = (bytes / 1000000000).toFixed(2) + &#8216; GB&#8217;; }<br />
        else if (bytes &gt;= 1000000) { bytes = (bytes / 1000000).toFixed(2) + &#8216; MB&#8217;; }<br />
        else if (bytes &gt;= 1000) { bytes = (bytes / 1000).toFixed(2) + &#8216; KB&#8217;; }<br />
        else if (bytes &gt; 1) { bytes = bytes + &#8216; bytes&#8217;; }<br />
        else if (bytes == 1) { bytes = bytes + &#8216; byte&#8217;; }<br />
        else { bytes = &#8216;0 byte&#8217;; }<br />
        return bytes;<br />
    }<br />
[/js]</p>
<p>As you can see in the <a href="http://sibeeshpassion.com/tag/ajax/" target="_blank">AJAX </a>call we have set URL as <em>http://localhost:5022/Home/UploadFile</em> so we need to create a JsonResult/ActionResult in our Home controller right? I will create an asynchronous JsonResult action there.</p>
<p>[csharp]<br />
#region UploadImages<br />
        /// &lt;summary&gt;<br />
        /// Upload images to the cloud and database. User can upload a single image or a collection of images.<br />
        /// &lt;/summary&gt;<br />
        [HttpPost]<br />
        public async Task&lt;JsonResult&gt; UploadFile()<br />
        {<br />
            try<br />
            {<br />
                List&lt;ImageLists&gt; prcssdImgLists = null;<br />
                if (HttpContext.Request.Files.AllKeys.Any())<br />
                {<br />
                    var httpPostedFile = HttpContext.Request.Files;<br />
                    if (httpPostedFile != null)<br />
                    {<br />
                        string result = string.Empty;<br />
                        string returnJson = string.Empty;<br />
                        using (var ah = new AzureHelper())<br />
                        {<br />
                            List&lt;Stream&gt; strmLists = new List&lt;Stream&gt;();<br />
                            List&lt;string&gt; lstContntTypes = new List&lt;string&gt;();<br />
                            for (int i = 0; i &lt; httpPostedFile.Count; i++)<br />
                            {<br />
                                strmLists.Add(httpPostedFile[i].InputStream);<br />
                                lstContntTypes.Add(httpPostedFile[i].ContentType);<br />
                            }<br />
                            prcssdImgLists = await ah.UploadImages(strmLists, lstContntTypes);<br />
                        }</p>
<p>                    }<br />
                }<br />
                return Json(prcssdImgLists, JsonRequestBehavior.AllowGet);<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
        }<br />
        #endregion<br />
[/csharp]</p>
<p>There we are getting the uploaded files from <em>HttpContext.Request.Files</em>. Did you notice that we are returning the data as collection of the class <em>ImageLists</em>? Where is our <em>ImageLists </em>class then?</p>
<p>[csharp]<br />
using System;<br />
using System.IO;</p>
<p>namespace WorkingWithImagesAndAzure.Models<br />
{<br />
    /// &lt;summary&gt;<br />
    /// Image Collection, describes the properties of the image uploaded<br />
    /// &lt;/summary&gt;<br />
    public class ImageLists<br />
    {<br />
        #region Private Collections<br />
        private Guid _imageID = Guid.Empty;<br />
        private string _imageTitle = string.Empty;<br />
        private string _imageData = string.Empty;<br />
        private string _assetID = string.Empty;<br />
        private long _imageSize = 0;<br />
        #endregion</p>
<p>        #region Public Properties<br />
        /// &lt;summary&gt;<br />
        /// The GUID of image<br />
        /// &lt;/summary&gt;<br />
        public Guid ImageID<br />
        {<br />
            get<br />
            {<br />
                return _imageID;<br />
            }<br />
            set<br />
            {<br />
                if (value != Guid.Empty &amp;&amp; value != _imageID)<br />
                {<br />
                    _imageID = value;<br />
                }<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// The name of the image, a string value<br />
        /// &lt;/summary&gt;<br />
        public string Title<br />
        {<br />
            get<br />
            {<br />
                return _imageTitle;<br />
            }<br />
            set<br />
            {<br />
                if (value != string.Empty &amp;&amp; value != _imageTitle)<br />
                    _imageTitle = value;<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// AssetID<br />
        /// &lt;/summary&gt;<br />
        public string AssetID<br />
        {<br />
            get<br />
            {<br />
                return _assetID;<br />
            }<br />
            set<br />
            {<br />
                if (value != string.Empty &amp;&amp; value != _assetID)<br />
                    _assetID = value;<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// The filesteam of the single image uploaded<br />
        /// &lt;/summary&gt;<br />
        public string ImageData<br />
        {<br />
            get<br />
            {<br />
                return _imageData;<br />
            }<br />
            set<br />
            {<br />
                if (value != null &amp;&amp; value != _imageData)<br />
                    _imageData = value;<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// ImageSize<br />
        /// &lt;/summary&gt;<br />
        public long ImageSize<br />
        {<br />
            get<br />
            {<br />
                return _imageSize;<br />
            }<br />
            set<br />
            {<br />
                if (value != 0 &amp;&amp; value != _imageSize)<br />
                    _imageSize = value;<br />
            }<br />
        }<br />
        #endregion</p>
<p>    }<br />
}<br />
[/csharp]</p>
<p>Yes you are right, we need to create an another class too, <em>AzureHelper</em>. </p>
<p>[csharp]<br />
 public class AzureHelper : IDisposable<br />
    {<br />
        void IDisposable.Dispose()<br />
        {</p>
<p>        }<br />
    }<br />
[/csharp]</p>
<p>Here we will start all of our codes related to media service account. Before going further, please install <em>Microsoft.WindowsAzure.Storage</em> from NuGet package manager. And add the following references.</p>
<p>[csharp]<br />
using ImageResizer;<br />
using Microsoft.WindowsAzure.MediaServices.Client;<br />
using Microsoft.WindowsAzure.Storage;<br />
using Microsoft.WindowsAzure.Storage.Blob;<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Configuration;<br />
using System.IO;<br />
using System.Threading.Tasks;<br />
[/csharp]</p>
<p>You must add ImageResizer.dll to your references before you start using ImageResizer, you can get the DLL file from the source code attached. </p>
<p>Next, we will configure our <em>Web.config</em> with the keys and connection strings we needed. When I said, keys, it includes your media service account keys too, if you don&#8217;t know your media service account keys, please login to your azure portal and get it by selecting your media service account. We will be adding the following keys, please replace the information with yours.</p>
<p>[xml]<br />
&lt;appSettings&gt;<br />
    &lt;add key=&quot;webpages:Version&quot; value=&quot;3.0.0.0&quot; /&gt;<br />
    &lt;add key=&quot;webpages:Enabled&quot; value=&quot;false&quot; /&gt;<br />
    &lt;add key=&quot;ClientValidationEnabled&quot; value=&quot;true&quot; /&gt;<br />
    &lt;add key=&quot;UnobtrusiveJavaScriptEnabled&quot; value=&quot;true&quot; /&gt;<br />
    &lt;add key=&quot;imgRszeWdth&quot; value=&quot;120&quot; /&gt;<br />
    &lt;add key=&quot;imgRszeHgth&quot; value=&quot;120&quot; /&gt;<br />
    &lt;add key=&quot;myAzureStorageCon&quot; value=&quot;UseDevelopmentStorage=true;&quot; /&gt;<br />
    &lt;add key=&quot;MediaServicesAccountName&quot; value=&quot;&quot; /&gt;<br />
    &lt;add key=&quot;MediaServicesAccountKey&quot; value=&quot;&quot; /&gt;<br />
    &lt;add key=&quot;myAzureStorageConSetting&quot; value=&quot;&quot; /&gt;<br />
  &lt;/appSettings&gt;<br />
[/xml]</p>
<p>Now we can set our connection strings of both storage account and media service account. </p>
<p>[xml]<br />
 &lt;add name=&quot;myAzureStorageCon&quot; connectionString=&quot;DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=youraccountkey&quot; /&gt;<br />
    &lt;add name=&quot;MediaStorage&quot; connectionString=&quot;DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=youraccountkey&quot; /&gt;<br />
[/xml]</p>
<p>I hope you have set everything. Now we can create the functions and constants we need in our AzureHelper class. Are you ready?</p>
<p>[csharp]<br />
 #region Constants<br />
        private static readonly string imgRszeWdth = ConfigurationManager.AppSettings[&quot;imgRszeWdth&quot;];<br />
        private static readonly string imgRszeHgth = ConfigurationManager.AppSettings[&quot;imgRszeHgth&quot;];<br />
        private static readonly string mediaServicesAccountName = ConfigurationManager.AppSettings[&quot;MediaServicesAccountName&quot;];<br />
        private static readonly string mediaServicesAccountKey = ConfigurationManager.AppSettings[&quot;MediaServicesAccountKey&quot;];<br />
        private static readonly string myAzureStorageConSetting = ConfigurationManager.AppSettings[&quot;myAzureStorageConSetting&quot;];<br />
        private static readonly string myAzureCon = ConfigurationManager.ConnectionStrings[&quot;MediaStorage&quot;].ConnectionString;<br />
        #endregion<br />
[/csharp]</p>
<p>And we need to create a function named <em>UploadImages</em>, this is the one we are calling from our controller. </p>
<p>[csharp]<br />
 #region Public Methods<br />
        public async Task&lt;List&lt;ImageLists&gt;&gt; UploadImages(List&lt;Stream&gt; strmLists, List&lt;string&gt; lstContntTypes)<br />
        {<br />
            string myContainerName = &quot;Test007&quot;;<br />
            string assetID = CreateBLOBContainer(myContainerName);<br />
            assetID = assetID.Replace(&quot;nb:cid:UUID:&quot;, &quot;asset-&quot;);<br />
            List&lt;ImageLists&gt; retCollection = new List&lt;ImageLists&gt;();<br />
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(myAzureStorageConSetting);<br />
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();<br />
            CloudBlobContainer container = blobClient.GetContainerReference(assetID);<br />
            container.SetPermissions(<br />
              new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });</p>
<p>            if (strmLists != null)<br />
            {<br />
                for (int i = 0; i &lt; strmLists.Count; i++)<br />
                {<br />
                    string strExtension = string.Empty;<br />
                    if (lstContntTypes[i] == &quot;image/gif&quot;)<br />
                    {<br />
                        strExtension = &quot;.gif&quot;;<br />
                    }<br />
                    else if (lstContntTypes[i] == &quot;image/jpeg&quot;)<br />
                    {<br />
                        strExtension = &quot;.jpeg&quot;;<br />
                    }<br />
                    else if (lstContntTypes[i] == &quot;image/jpg&quot;)<br />
                    {<br />
                        strExtension = &quot;.jpg&quot;;<br />
                    }<br />
                    else if (lstContntTypes[i] == &quot;image/png&quot;)<br />
                    {<br />
                        strExtension = &quot;.png&quot;;<br />
                    }<br />
                    ImageLists img = new ImageLists();<br />
                    string imgGUID = Guid.NewGuid().ToString();<br />
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(string.Concat(imgGUID, strExtension));<br />
                    await blockBlob.UploadFromStreamAsync(strmLists[i]);</p>
<p>                    img.ImageID = new Guid(imgGUID);<br />
                    img.Title = string.Concat(imgGUID, strExtension);<br />
                    img.ImageSize = strmLists[i].Length;<br />
                    img.AssetID = assetID;<br />
                    retCollection.Add(img);</p>
<p>                    CloudBlockBlob blockblobthumb = container.GetBlockBlobReference(string.Concat(imgGUID, &quot;_thumb&quot;, strExtension));<br />
                    Stream strmThumb = ResizeImage(strmLists[i]);<br />
                    using (strmThumb)<br />
                    {<br />
                        await blockblobthumb.UploadFromStreamAsync(strmThumb);</p>
<p>                        img = new ImageLists();<br />
                        img.ImageID = new Guid(imgGUID);<br />
                        img.Title = string.Concat(imgGUID, &quot;_thumb&quot;, strExtension);<br />
                        img.ImageSize = strmThumb.Length;<br />
                        img.AssetID = assetID;<br />
                        retCollection.Add(img);<br />
                    }<br />
                }</p>
<p>            }<br />
            return retCollection;<br />
        }<br />
        #endregion<br />
[/csharp]</p>
<p>As you can see we are creating the asset as <em>CreateBLOBContainer(myContainerName)</em>. So shall we see the function now?</p>
<p>[csharp]<br />
 private string CreateBLOBContainer(string containerName)<br />
        {<br />
            try<br />
            {<br />
                string result = string.Empty;<br />
                CloudMediaContext mediaContext;<br />
                mediaContext = new CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey);<br />
                IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);<br />
                return asset.Id;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>That&#8217;s fantastic, we just created an asset in our media service account. And this is the code  <em>await blockBlob.UploadFromStreamAsync(strmLists[i]);</em> which does the uploading. Once the actual image is uploaded we are passing the stream to a function <em>ResizeImage(strmLists[i])</em> which will return the converted stream. </p>
<p>[csharp]<br />
 private static MemoryStream ResizeImage(Stream downloaded)<br />
        {<br />
            var memoryStream = new MemoryStream();<br />
            var settings = string.Format(&quot;mode=crop&amp;width={0}&amp;height={1}&quot;, Convert.ToInt32(imgRszeWdth), Convert.ToInt32(imgRszeHgth));<br />
            downloaded.Seek(0, SeekOrigin.Begin);<br />
            var i = new ImageJob(downloaded, memoryStream, new Instructions(settings));<br />
            i.Build();<br />
            memoryStream.Position = 0;<br />
            return memoryStream;<br />
        }<br />
[/csharp]</p>
<p>Once we finished uploading we are creating an output as follows.</p>
<p>[csharp]<br />
  ImageLists img = new ImageLists();<br />
   img.ImageID = new Guid(imgGUID);<br />
                    img.Title = string.Concat(imgGUID, strExtension);<br />
                    img.ImageSize = strmLists[i].Length;<br />
                    img.AssetID = assetID;<br />
                    retCollection.Add(img);<br />
[/csharp]</p>
<p>All good? Build your application and run!. Can you see outputs as below?</p>
<div id="attachment_11746" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11746" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-1024x380.png" alt="Upload Images To Azure Media Service Home Page" width="634" height="235" class="size-large wp-image-11746" srcset="/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-1024x380.png 1024w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-300x111.png 300w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-768x285.png 768w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-400x149.png 400w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page.png 1195w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11746" class="wp-caption-text">Upload Images To Azure Media Service Home Page</p></div>
<p>Click on the link <em>Upload Images</em>, you can see the Upload view now.</p>
<div id="attachment_11747" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720.png"><img decoding="async" aria-describedby="caption-attachment-11747" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720.png" alt="Upload Images To Azure Media Service Upload View" width="650" height="237" class="size-full wp-image-11747" srcset="/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720.png 650w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720-300x109.png 300w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720-400x146.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11747" class="wp-caption-text">Upload Images To Azure Media Service Upload View</p></div>
<p>Now select the files and click on Submit.</p>
<div id="attachment_11748" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output.png"><img decoding="async" aria-describedby="caption-attachment-11748" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-1024x629.png" alt="Upload Images To Azure Media Service Output" width="634" height="389" class="size-large wp-image-11748" srcset="/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-1024x629.png 1024w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-300x184.png 300w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-768x472.png 768w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-400x246.png 400w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-977x600.png 977w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output.png 1107w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11748" class="wp-caption-text">Upload Images To Azure Media Service Output</p></div>
<p>You can select as many files as you wish.</p>
<div id="attachment_11751" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple.png"><img decoding="async" aria-describedby="caption-attachment-11751" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-1024x886.png" alt="Upload Images To Azure Media Service Output Multiple" width="634" height="549" class="size-large wp-image-11751" srcset="/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-1024x886.png 1024w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-300x260.png 300w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-768x664.png 768w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-400x346.png 400w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-693x600.png 693w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple.png 413w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11751" class="wp-caption-text">Upload Images To Azure Media Service Output Multiple</p></div>
<p>So we have uploaded both thumbnail and actual image. That&#8217;s cool. I guess we have done for now. Have a happy coding!.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Have you ever tried Azure media service account? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/upload-files-to-azure-media-service-from-server-side-in-mvc/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Programmatically Extract or Unzip Zip,Rar Files And Check</title>
		<link>https://www.sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/</link>
					<comments>https://www.sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 25 Feb 2016 00:00:22 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Extract Files]]></category>
		<category><![CDATA[HttpFileCollectionBase]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[System.IO.Compression]]></category>
		<category><![CDATA[System.IO.Compression.FileSystem]]></category>
		<category><![CDATA[Unzip Files]]></category>
		<category><![CDATA[Upload in MVC]]></category>
		<category><![CDATA[ZipArchive]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11281</guid>

					<description><![CDATA[In this pose we will see how we can extract or unzip the uploaded files and check for some files in it in a in a programmatic manner. We will use a normal MVC application to work with this demo. We will use Microsoft System.IO.Compression, System.IO.Compression.FileSystem namespaces and the classes, for example ZipArchive, in the namespace for extracting or unzipping the files we upload. Once it is uploaded we will check the same by looping through it. For the client side coding, we uses jQuery. I guess this is enough for the introduction, now we will move on to our [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this pose we will see how we can extract or unzip the uploaded files and check for some files in it in a in a programmatic manner. We will use a normal <a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC</a> application to work with this demo. We will use Microsoft System.IO.Compression, System.IO.Compression.FileSystem namespaces and the classes, for example ZipArchive, in the namespace for extracting or unzipping the files we upload. Once it is uploaded we will check the same by looping through it. For the client side coding, we uses <a href="http://sibeeshpassion.com/category/jQuery/" target="_blank" rel="noopener">jQuery</a>. I guess this is enough for the introduction, now we will move on to our application. Let us create it. I hope you will like this article. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: 	</p>
<li><a href="https://gallery.technet.microsoft.com/Programmatically-Extract-0544debd" target="_blank" rel="noopener">Programmatically Extract or Unzip Zip,Rar Files And Check</a></li>
<p><strong>Background</strong></p>
<p>As you are aware most websites accepts only .zip or any other zipped formats, this is for ensuring that only less amount of data is being uploaded to the server. We can reduce almost 60 percentage of the size if we zipped the same. Now the problem is, how you can validate any zipped item which is uploaded to your site? How can you check for any particular file in that zipped item? For example if you need to find out any files with extension of .sql, .ico or .txt? What if you want to intimate user that the uploaded items does not have any particular file that must be needed? You need to loop through the contents available in it right? This is what we are going to discuss in this post. I had a situation of uploading my old back ups of my personal website (<a href="http://sibeeshpassion.com/" target="_blank" rel="noopener">http://sibeeshpassion.com/</a>) and after uploading I wanted to check whether the uploaded .zip file has .ico file in it. The process we are going to do is listed below.</p>
<li>Create a MVC application</li>
<li>Install jQuery</li>
<li>Create Controller and View</li>
<li>Upload Action Using jQuery</li>
<li>Add System.IO.Compression, System.IO.Compression.FileSystem references</li>
<li>Checks for the file using ZipArchive class</li>
<p><strong>Using the code</strong></p>
<p>Now we will move into the coding part. I hope your MVC application is ready for action 🙂 with all the needed packages. </p>
<p><strong>Create a controller</strong></p>
<p>Now we will create a controller, view with an action in it as follows. </p>
<p>[csharp]<br />
public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
[/csharp]</p>
<p><strong>Update the view</strong></p>
<p>Now in the view, we will add a file upload and other needed elements. </p>
<p>[html]<br />
&lt;input type=&quot;file&quot; name=&quot;FileUpload1&quot; id=&quot;fileUpload&quot; placeholder=&quot;Please select the file&quot; /&gt;&lt;br /&gt;<br />
&lt;input id=&quot;btnUploadFile&quot; type=&quot;button&quot; value=&quot;Upload File&quot; /&gt;<br />
&lt;div id=&quot;message&quot;&gt;&lt;/div&gt;<br />
[/html]</p>
<p><strong>Add the JS references</strong></p>
<p>Add the references as follows.</p>
<p>[html]<br />
&lt;script src=&quot;~/scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/MyScript.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Here <em>MyScript.js</em> is where we are going to write some scripts. </p>
<p><strong>Style the elements (Optional) </strong></p>
<p>You can style your view as follows. This step is absolutely optional, for me the view should not as simple as default one. And to be frank I am not a good designer 🙂</p>
<p>[css]<br />
&lt;style&gt;<br />
    #fileUpload {<br />
        border: 1px solid #ccc;<br />
        padding: 10px;<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
    }</p>
<p>    #btnUploadFile {<br />
        border: 1px solid #ccc;<br />
        padding: 10px;<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
    }</p>
<p>    #message {<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
        margin-top: 15px;<br />
    }<br />
    h2 {<br />
        border-radius: 5px;<br />
        font-size: 20px;<br />
        font-family: cursive;<br />
        color: blue;<br />
        margin-top: 15px;<br />
    }<br />
&lt;/style&gt;<br />
[/css]</p>
<p><strong>Add the upload action in script</strong></p>
<p>Now it is time to create upload action. For that, please go to the script file MyScript.js and do the coding as follows. </p>
<p>[js]<br />
$(document).ready(function () {<br />
    $(&#8216;#btnUploadFile&#8217;).on(&#8216;click&#8217;, function () {<br />
        var data = new FormData();<br />
        var files = $(&quot;#fileUpload&quot;).get(0).files;<br />
        // Add the uploaded image content to the form data collection<br />
        if (files.length &gt; 0) {<br />
            data.append(&quot;UploadedImage&quot;, files[0]);<br />
        }<br />
        // Make Ajax request with the contentType = false, and procesDate = false<br />
        var ajaxRequest = $.ajax({<br />
            type: &quot;POST&quot;,<br />
            url: &quot;Home/Upload&quot;,<br />
            contentType: false,<br />
            processData: false,<br />
            data: data,<br />
            success: function (data) {<br />
                $(&#8216;#message&#8217;).html(data);<br />
            },<br />
            error: function (e)<br />
            {<br />
                console.log(&#8216;Oops, Something went wrong!.&#8217; + e.message);<br />
            }<br />
        });<br />
        ajaxRequest.done(function (xhr, textStatus) {<br />
            // Do other operation<br />
        });<br />
    });<br />
});<br />
[/js]</p>
<p>If you are not aware of uploading and downloading in MVC, I strongly recommend you to have a look here: <a href="http://sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/" target="_blank" rel="noopener">Uploading and Downloading in MVC Step-by-Step</a>. </p>
<p>So we have set Home/Upload as the URL action in our <a href="http://sibeeshpassion.com/tag/jquery-ajax/" target="_blank" rel="noopener">Ajax</a> function right? So we are going to create that action. Go to your controller and create a JsonResult action as follows. </p>
<p>[csharp]<br />
public JsonResult Upload()<br />
        {<br />
            string isValid = checkIsValid(Request.Files);<br />
            return Json(isValid, JsonRequestBehavior.AllowGet);<br />
        }<br />
[/csharp]</p>
<p>So we have done that too, now stop for a while. To work with <em>ZipArchive</em> class you must include the namespace as listed below. </p>
<p>[csharp]<br />
using System.IO.Compression;<br />
[/csharp]</p>
<p>Now you will be shown an error as &#8220;Are you missing an assembly reference?&#8221;. Yes we are. We have not added that references right? So now we are going to add the references for System.IO.Compression and System.IO.Compression.FileSystem. </p>
<p>Right click on Reference in your project and browse for the references. If you uses Visual Studio 2015, the references will be in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6. </p>
<blockquote><p>Please be noted that the folder names will differs according to your framework version</p></blockquote>
<div id="attachment_11282" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Compression_References-e1455888597687.png"><img decoding="async" aria-describedby="caption-attachment-11282" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Compression_References-e1455888597687.png" alt="Compression_References" width="650" height="447" class="size-full wp-image-11282" srcset="/wp-content/uploads/2016/02/Compression_References-e1455888597687.png 650w, /wp-content/uploads/2016/02/Compression_References-e1455888597687-300x206.png 300w, /wp-content/uploads/2016/02/Compression_References-e1455888597687-160x110.png 160w, /wp-content/uploads/2016/02/Compression_References-e1455888597687-400x275.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11282" class="wp-caption-text">Compression_References</p></div>
<p>Now we will go back to our controller and write the codes for the function <em>checkIsValid(Request.Files)</em></p>
<p>[csharp]<br />
private string checkIsValid(HttpFileCollectionBase files)<br />
        {<br />
            string isValid = string.Empty;<br />
            try<br />
            {<br />
                foreach (string upload in Request.Files)<br />
                {<br />
                    if (Request.Files[upload].ContentType == &quot;application/octet-stream&quot;) //Content type for .zip is application/octet-stream<br />
                    {<br />
                        if (Request.Files[upload].FileName != &quot;&quot;)<br />
                        {<br />
                            string path = AppDomain.CurrentDomain.BaseDirectory + &quot;/ App_Data / uploads /&quot;;<br />
                            if (!Directory.Exists(path))<br />
                            {<br />
                                // Try to create the directory.<br />
                                DirectoryInfo di = Directory.CreateDirectory(path);<br />
                            }</p>
<p>                            string filename = Path.GetFileName(Request.Files[upload].FileName);<br />
                            string pth = Path.Combine(path, filename);<br />
                            Request.Files[upload].SaveAs(pth);<br />
                            isValid = CheckForTheIcon(pth);<br />
                        }<br />
                    }<br />
                    else<br />
                    {<br />
                        isValid = &quot;Only .zip files are accepted.&quot;;<br />
                    }<br />
                }<br />
                return isValid;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                return &quot;Oops!. Something went wrong&quot;;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>As you can see we are looping through the <em>HttpFileCollectionBase</em> files and checks for the content type first. </p>
<blockquote><p>Please be noted that the content type for the .zip file is application/octet-stream</p></blockquote>
<p>Once the checking is done, we will save the files to a folder, we will send the path to the function <em>CheckForTheIcon(pth)</em>. So our next thing we need to do is to create the function CheckForTheIcon().</p>
<p>[csharp]<br />
  private string CheckForTheIcon(string strPath)<br />
        {<br />
            string result = string.Empty;<br />
            try<br />
            {<br />
                using (ZipArchive za = ZipFile.OpenRead(strPath))<br />
                {<br />
                    foreach (ZipArchiveEntry zaItem in za.Entries)<br />
                    {<br />
                        if (zaItem.FullName.EndsWith(&quot;.ico&quot;, StringComparison.OrdinalIgnoreCase))<br />
                        {<br />
                            result = &quot;Success&quot;;<br />
                        }<br />
                        else<br />
                        {<br />
                            result = &quot;No ico files has been found&quot;;<br />
                        }<br />
                    }<br />
                }<br />
                return result;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                result = &quot;Oops!. Something went wrong&quot;;<br />
                return result;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>As you can see we are looping through each <em>ZipArchive</em> class items and checks for the &#8216;.ico&#8217; file in it. So if there is no error and there is &#8216;.ico&#8217; file in the uploaded item zip item, you will get the message as &#8220;Success: or if it does not contain the &#8216;.ico&#8217; file, you will get the message as &#8220;No ico files has been found&#8221;. </p>
<p>Now it is time to see our output. Please run your application. </p>
<p><strong>Output</strong></p>
<div id="attachment_11283" style="width: 638px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item.png"><img decoding="async" aria-describedby="caption-attachment-11283" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item.png" alt="If_you_try_to_upload_not_zipped_item" width="628" height="298" class="size-full wp-image-11283" srcset="/wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item.png 628w, /wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item-300x142.png 300w, /wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item-400x190.png 400w" sizes="(max-width: 628px) 100vw, 628px" /></a><p id="caption-attachment-11283" class="wp-caption-text">If_you_try_to_upload_not_zipped_item</p></div>
<div id="attachment_11284" style="width: 653px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file.png"><img decoding="async" aria-describedby="caption-attachment-11284" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file.png" alt="If_you_try_to_upload_zipped_item_which_does_not_have_ico_file" width="643" height="288" class="size-full wp-image-11284" srcset="/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file.png 643w, /wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file-300x134.png 300w, /wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file-400x179.png 400w" sizes="(max-width: 643px) 100vw, 643px" /></a><p id="caption-attachment-11284" class="wp-caption-text">If_you_try_to_upload_zipped_item_which_does_not_have_ico_file</p></div>
<div id="attachment_11285" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121.png"><img decoding="async" aria-describedby="caption-attachment-11285" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121.png" alt="If_you_try_to_upload_zipped_item_which_have_ico_file" width="650" height="277" class="size-full wp-image-11285" srcset="/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121.png 650w, /wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121-300x128.png 300w, /wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121-400x170.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11285" class="wp-caption-text">If_you_try_to_upload_zipped_item_which_have_ico_file</p></div>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Uploading and Downloading in MVC Step-by-Step</title>
		<link>https://www.sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/</link>
					<comments>https://www.sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 14 Jun 2015 01:00:52 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Download in MVC]]></category>
		<category><![CDATA[File Downloading Using MVC]]></category>
		<category><![CDATA[File Uploading Using MVC]]></category>
		<category><![CDATA[Model View Controller]]></category>
		<category><![CDATA[MVC Download]]></category>
		<category><![CDATA[MVC Upload]]></category>
		<category><![CDATA[Upload in MVC]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=1931</guid>

					<description><![CDATA[Introduction I hope you all are fine. Today we will learn how to perform upload and download operations in MVC. Please refer to the step-by-step approach in learning Model View Controller if you are new to MVC. Our MVC Master, Shivprasad koirala has explained the concepts in a perfect way. Download the source code Uploading and Downloading in MVC Step-by-Step Background Some days earlier, I got a requirement to develop a upload and download mechanism in my MVC application. After completing it perfectly, I decided to share it with you all. Using the code Before moving further into the details, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>I hope you all are fine. Today we will learn how to perform upload and download operations in MVC. Please refer to the <a href="http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in" target="_blank" rel="noopener">step-by-step approach</a> in learning Model View Controller if you are new to MVC. Our MVC Master, Shivprasad koirala has explained the concepts in a perfect way.</p>
<p><strong>Download the source code</strong></p>
<li><a href="https://code.msdn.microsoft.com/Uploading-and-Downloading-7b5277ef" target="_blank" rel="noopener">Uploading and Downloading in MVC Step-by-Step</a></li>
<p><strong>Background </strong></p>
<p>Some days earlier, I got a requirement to develop a upload and download mechanism in my MVC application. After completing it perfectly, I decided to share it with you all.</p>
<p><strong>Using the code</strong></p>
<p>Before moving further into the details, let us first list the key points we will explain in this article:</p>
<li>Create a MVC application.</li>
<li>Create a controller.</li>
<li>Create View depending on the controller.</li>
<li>Change the RouteConfig as needed.</li>
<li>Create ActionResult for the actions.</li>
<li>Create a folder where we need to save the downloaded files.</li>
<p>Let us start with creating a controller called “myAction”.<br />
[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.IO;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Mvc;<br />
namespace UploadDownloadInMVC.Controllers<br />
{<br />
    public class myActionController : Controller<br />
    {<br />
        //<br />
        // GET: /myAction/<br />
    }<br />
}<br />
[/csharp]</p>
<p>As you can see that the controller is empty; we will be writing the action results next.<br />
[csharp]<br />
public ActionResult Index()<br />
       {<br />
           foreach (string upload in Request.Files)<br />
           {<br />
               if (Request.Files[upload].FileName != “”)<br />
               {<br />
                   string path = AppDomain.CurrentDomain.BaseDirectory + “/App_Data/uploads/”;<br />
                   string filename = Path.GetFileName(Request.Files[upload].FileName);<br />
                   Request.Files[upload].SaveAs(Path.Combine(path, filename));<br />
               }<br />
           }<br />
           return View(“Upload”);<br />
       }<br />
[/csharp]</p>
<p>The action result shown above is for index. So, whenever the application loads, the action result will be fired. For that, the following changes should be done for RouteCofig.<br />
[csharp]<br />
public class RouteConfig<br />
    {<br />
        public static void RegisterRoutes(RouteCollection routes)<br />
        {<br />
            routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);<br />
            routes.MapRoute(<br />
                name: “Default”,<br />
                url: “{controller}/{action}/{id}”,<br />
                defaults: new { controller = “myAction”, action = “Index”, id = UrlParameter.Optional }<br />
            );<br />
        }<br />
    }<br />
[/csharp]</p>
<p>As you can see in the Index Action,  we are checking whether the request parameter contains the files. If it exists, we will save the selected file to the directory</p>
<p><em>/App_Data/uploads/</em> (that we need to manually create in our application). After returning to the view Upload, we need to set the Upload view.</p>
<p><strong>Upload View</strong></p>
<p>The following is the code for the Upload view.<br />
[html]<br />
@{<br />
    ViewBag.Title = “Upload”;<br />
}<br />
&lt;h2&gt;Upload&lt;/h2&gt;<br />
&lt;script src=“~/Scripts/jquery-1.11.1.min.js”&gt;&lt;/script&gt;<br />
&lt;script&gt;<br />
    $(document).ready(function () {<br />
        $(‘#btnUploadFile’).on(‘click’, function () {<br />
            var data = new FormData();<br />
            var files = $(“#fileUpload”).get(0).files;<br />
            // Add the uploaded image content to the form data collection<br />
            if (files.length &gt; 0) {<br />
                data.append(“UploadedImage”, files[0]);<br />
            }<br />
            // Make Ajax request with the contentType = false, and procesDate = false<br />
            var ajaxRequest = $.ajax({<br />
                type: “POST”,<br />
                url: “myAction/Index”,<br />
                contentType: false,<br />
                processData: false,<br />
                data: data<br />
            });<br />
            ajaxRequest.done(function (xhr, textStatus) {<br />
                // Do other operation<br />
            });<br />
        });<br />
    });<br />
&lt;/script&gt;<br />
&lt;input type=“file” name=“FileUpload1″ id=“fileUpload” /&gt;&lt;br /&gt;<br />
&lt;input id=“btnUploadFile” type=“button” value=“Upload File” /&gt;<br />
@Html.ActionLink(“Documents”, “Downloads”)<br />
[/html]</p>
<p>In the upload view, we have the following:</p>
<li>File uploader</li>
<li>Upload button</li>
<li>Ajax call to the controller ( myAction/Index)</li>
<p>Here, we are adding the uploaded image content to the form data collection.<br />
[csharp]<br />
var data = new FormData();<br />
           var files = $(“#fileUpload”).get(0).files;<br />
           // Add the uploaded image content to the form data collection<br />
           if (files.length &gt; 0) {<br />
               data.append(“UploadedImage”, files[0]);<br />
           }<br />
[/csharp]</p>
<p>Once the data is added to the form data collection, we will pass the data to the controller via ajax call. Sounds cool, right? If the procedure goes well, we will see the output as follows.</p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/uploading-and-downloading-in-mvc/Images/upload1.PNG" alt="" /></p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/uploading-and-downloading-in-mvc/Images/upload2.PNG" alt="" /></p>
<p>When you choose the file and click upload, your selected file will be uploaded to the folder “uploads” as we have set it in the controller.</p>
<p>We have finished the process of uploading files. We will now move to the downloading section. This is the right time to add the remaining actions to our controller. The following is the code.<br />
[csharp]<br />
public ActionResult Downloads()<br />
        {<br />
            var dir = new System.IO.DirectoryInfo(Server.MapPath(“~/App_Data/uploads/”));<br />
            System.IO.FileInfo[] fileNames = dir.GetFiles(“*.*”); List&lt;string&gt; items = new List&lt;string&gt;();<br />
            foreach (var file in fileNames)<br />
            {<br />
                items.Add(file.Name);<br />
            }<br />
            return View(items);<br />
        }<br />
        public FileResult Download(string ImageName)<br />
        {<br />
            var FileVirtualPath = “~/App_Data/uploads/” + ImageName;<br />
            return File(FileVirtualPath, “application/force-download”, Path.GetFileName(FileVirtualPath));<br />
        }<br />
[/csharp]</p>
<p>Do you remember that we have set an action link in the “Upload” View?<br />
[html]<br />
@Html.ActionLink(“Documents”, “Downloads”)<br />
[/html]</p>
<p>Next, if we click on the “Documents” link, our Action Result Downloads will be fired, right? Now, the following code will explain what is happening here.<br />
[csharp]<br />
var dir = new System.IO.DirectoryInfo(Server.MapPath(“~/App_Data/uploads/”));<br />
            System.IO.FileInfo[] fileNames = dir.GetFiles(“*.*”); List&lt;string&gt; items = new List&lt;string&gt;();<br />
            foreach (var file in fileNames)<br />
            {<br />
                items.Add(file.Name);<br />
            }<br />
            return View(items);<br />
[/csharp]</p>
<p>We are considering all the attached files, adding the file information to a list and returning this list to the view “Download”. Next, here’s the need to set another view. The following code is for the Download View.</p>
<p><strong>Download View</strong><br />
[html]<br />
@{<br />
    ViewBag.Title = “Downloads”;<br />
}<br />
&lt;h2&gt;Downloads&lt;/h2&gt;<br />
@model List&lt;string&gt;<br />
&lt;h2&gt;Downloads&lt;/h2&gt;<br />
&lt;table&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;File Name&lt;/th&gt;<br />
        &lt;th&gt;Link&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    @for (var i = 0; i &lt;= Model.Count – 1; i++)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;@Model[i].ToString() &lt;/td&gt;<br />
            &lt;td&gt;@Html.ActionLink(“Download”, “Download”, new { ImageName = @Model[i].ToString() }) &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
[/html]</p>
<p>Here, we are taking the information (that we are sending from the controller) about the uploaded files and creating the Html.ActionLinks dynamically.</p>
<p>Please note that we are adding the Image name to the  action. Here is the output after performing the operations.</p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/uploading-and-downloading-in-mvc/Images/downloadWithframe.png" alt="" /></p>
<p>As in the preceding image, when you mouse over the link, it will show the image name along with the controller URL. Click on the link to download the file. So simple, right?</p>
<p><strong>Conclusion</strong></p>
<p>I hope you liked the article. Please provide your valuable feedback; it matters a lot. You can download the source code to determine more.</p>
<p><strong>Point of interest</strong></p>
<p>MVC, MVC Upload, MVC Download, File Uploading Using MVC, File Downloading Using MVC</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
