ASP.NET MVC

How To Upload Images Using Cloudinary In ASP.Net MVC

In This Blog,  We Are Going To Learn  How To Images Upload Using Cloudinary In ASP.Net MVC.

Step 1:-  First You need to Create an Account In Cloud nary,  Go To This Link and Click On Sing Up For Free Button. If You Already Created Cloud nary Account Then Go To Step 5 Directly Else Follow Step 1 To Step 4.

 

Step 2:- Fill Up All The  Details Below the Sign Up Form And Create An Account.

Step 3:- After Create An Account Click On Login Button And Enter Your Credential & Login It.

Step 4: After  Sign In Go To The Dashboard And You See Your Account Details.


Step 5: Now Create New Project In ASP.NET MVC.

 

Step 6: Now Select Empty Template And Core Reference As MVC.

Step 7: Now Go To Your Cloudinary Account And Copy Your Account Details Like, “Cloud Name“, “API Key“, “API Secret“.

Step 8: Now Open Your Web Config And Add The Cloudinary Account Details.

Step 9: You Need To Install  CloudinaryDotNet NuGet Package To Your Project.

Step 10: Now Add References In Our Controller.

Step 11: Here Is Our Cloudinary Controller Side Source Code As Below.

using System;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using CloudinaryDotNet;
using CloudinaryDotNet.Actions;
using System.Text.RegularExpressions;
using System.Drawing;

namespace DemoCloudinary.Controllers
{
    public class CloudinaryController : Controller
    {
        // GET: Cloudinary
        public ActionResult ImageUpload()
        {
            return View();
        }

        [HttpPost]
        public bool SaveImageToServer()
        {
            try
            {
                HttpFileCollectionBase files = Request.Files;
                HttpPostedFileBase file = files[0];
                string _apiKey = ConfigurationManager.AppSettings["CloudinaryAPIKey"];
                string _apiSecret = ConfigurationManager.AppSettings["CloudinarySecretKey"];
                string _cloud = ConfigurationManager.AppSettings["CloudinaryAccount"];
                string uploadedImageUrl = string.Empty;
                string fname = string.Empty;
                var myAccount = new Account { ApiKey = _apiKey, ApiSecret = _apiSecret, Cloud = _cloud };
                Cloudinary _cloudinary = new Cloudinary(myAccount);

                // Checking for Internet Explorer  
                if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    fname = testfiles[testfiles.Length - 1];
                }
                else
                {
                    fname = Regex.Replace(file.FileName.Trim(), @"[^0-9a-zA-Z.]+", "_");
                }

                using (Image img = Image.FromStream(file.InputStream))
                {
                    int imageHeight = 0;
                    int imageWidth = 0;
                    if (img.Height > 320)
                    {
                        var ratio = (double)img.Height / 320;
                        imageHeight = (int)(img.Height / ratio);
                        imageWidth = (int)(img.Width / ratio);
                    }
                    else
                    {
                        imageHeight = img.Height;
                        imageWidth = img.Width;
                    }
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.FileName, file.InputStream),
                        Folder = "MyImages",
                        Transformation = new Transformation().Width(imageWidth).Height(imageHeight).Crop("thumb").Gravity("face")
                    };

                    var uploadResult = _cloudinary.UploadLarge(uploadParams);
                    uploadedImageUrl = uploadResult?.SecureUri?.AbsoluteUri;
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }

        }
    }

Step 12: The Source Code Of The Design Page Is Given Below.

@{
    ViewBag.Title = "ImageUpload";
}

<br />
<br />
<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

    <div class="container">
        <h2></h2>
        <div class="form-group">
            <label for="email">Images Upload:</label>
            <input type="file" class="form-control" id="filePhoto" placeholder="Upload File" name="File">
            <label id="ShowMsg"></label>
        </div>
        <button type="submit" class="btn btn-default" id="btnSubmit">Submit</button>
    </div>

</body>
</html>

Step 13: Here Is The Jquery Code After Click The Submit Button.

<script type="text/javascript">

    $("#btnSubmit").click(function () {
        var fileUpload = $("#filePhoto").get(0);
        var files = fileUpload.files;
        // Create FormData object
        var fileData = new FormData();
        // Looping over all files and add it to FormData object
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        var geturl = "Cloudinary/SaveImageToServer";
        $.ajax({
            url: geturl,
            type: "POST",
            data: fileData,
            async: false,
            contentType: false, // Not to set any content header
            processData: false, // Not to process data
            success: function (IsImageUploaded) {
                if (IsImageUploaded == "True") {
                    $("#filePhoto").val('');
                    $("#ShowMsg").text("Image Uploaded Successfully...!").css("color", "green")
                }
                else {
                    $("#filePhoto").val('');
                    $("#ShowMsg").text("Image Not Uploaded...!").css("color", "red")
                }
            }
        });
    })
</script>

 

step 10: Let’s See The Demo

 

Dipak Suthar

I am Dipak, .NET Developer | Software engineer | Blogger at thecodehubs.com. I have hands-on experience in Angular, .Net Core ,C#, ASP.NET MVC, ASP.NET, SQL SERVER, SQL Server Reporting Service (SSRS), C, C++, JavaScript, JQuery, AJAX, Bootstrap, JSON, XML, HTML, CSS. My main passion is learning new technologies and sharing knowledge, with programming I loves photography, traveling, and listening to songs. Engineering professional with a Bachelor of Computer Applications - BCA focused on Computer Science from Veer Narmad South Gujarat University, Surat.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago