.Net Image Upload in Cloudinary

Cloudinary In C#

Cloudinary is the market leader in providing a comprehensive cloud-based image management solution. Cloudinary is being used by tens of thousands of web and mobile application developers all around the world, from small startups to large enterprises. We are here to cover your every image-related need.


Cloud storage is the way

If you still write code to save files or images in a folder in your production/development server or even in the database, you are in trouble. I just hope you are aware of the consequences of doing that.

I built a class that allows you to upload, remove and download images from cloudinary which can be used in your web projects too. But, before you dive into coding, you have to register on cloudinary website and get an API key for development.

The Code

before we create the class, install the cloudinary package via nugget





using System.Collections.Generic;
using System.Web;
using CloudinaryDotNet;
using CloudinaryDotNet.Actions;

public class CloudinaryService {
 private readonly Cloudinary _cloudinary;

 /// <summary>
/// Set up cloudinary acccount 
/// </summary>
/// <param name="apiKey">The Api Key</param>
/// <param name="apiSecret">The Api Secret</param>
/// <param name="cloudName">Optional CloudName</param>


 public CloudinaryService(string apiKey = "apikey", string apiSecret = "apisecret",  string   cloudName = "cloudname") {
 var myAccount = new Account { ApiKey = apiKey, ApiSecret = apiSecret, Cloud =  cloudName }; 
_cloudinary = new Cloudinary(myAccount);
}

 /// <summary>
/// Upload image using HttpPostedFileBase
/// </summary>
/// <param name="file"></param>
/// <returns></returns>

 public ImageUploadResult UploadImage(HttpPostedFileBase file) {   if (file != null) {    var uploadParams = new ImageUploadParams {        File = new FileDescription(file.FileName,  file.InputStream),      Transformation = new     Transformation().Width(200).Height(200).Crop("thumb").Gravity("face")    };        var uploadResult = _cloudinary.Upload(uploadParams);     return uploadResult; } return null; 
/// <summary>/// Upload image using HttpPostedFile/// </summary>/// <param name="file"></param>/// <returns></returns>
 public ImageUploadResult UploadImage(HttpPostedFile file) {   if (file != null) {       var uploadParams = new ImageUploadParams { File = new  FileDescription(file.FileName,file.InputStream), Transformation = new  Transformation().Width(200).Height(200).Crop("thumb").Gravity("face")   }; var uploadResult = _cloudinary.Upload(uploadParams); return uploadResult; }  return null;
/// <summary>/// Delete a resource/// </summary>/// <param name="publicId"></param>
 public void DeleteResource(string publicId) { var delParams = new DelResParams() { PublicIds = new List() {publicId}, Invalidate = true }; _cloudinary.DeleteResources(delParams);   }}


The Web Api controller

There are three controllers for retrieving, uploading and deleting images from the clodinary server. The code is listed below:

     [Route("user/picture/{userId:int}")]
     [HttpPut]
     [Authorize]
    public async Task<IHttpActionResult> AddProfileImage(int userId)
    {
                var httpRequest = HttpContext.Current.Request;

                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    if (postedFile != null && postedFile.ContentLength > 0)
                    {
                        var result = new CloudinaryService().UploadImage(postedFile);
                        var user = await _uow.Repository<User>().GetAsync(userId);
                        user.profile.Picture = result.PublicId;
                        await _uow.SaveChangesAsync();
                        return Ok(result);
                     } return badRequest();
                }
               return NotFound();
     }   

        [Route("user/picture/{userId:int}")]
        [HttpGet]
        [Authorize]
        public async Task<IHttpActionResult> GetProfileImage(int userId)
        {
            var user = await _uow.Repository<User>().GetAsync(userId);
            if (user == null || string.IsNullOrEmpty(user.Profile.Picture))
            {
                return Content(HttpStatusCode.BadRequest,new
                {
                    data = "Picture is empty",
                    code=ResponseCodes.NoPicture
                });
            }
            return Ok(new
            {
                picture = user.Profile.Picture,
   
            });
        }

        [Route("user/picture/{userId:int}")]
        [HttpDelete]
        [Authorize]
        public async Task<IHttpActionResult> RemoveProfileImage(int userId)
        {
            var user = await _uow.Repository<User>().GetAsync(userId);
            if (user == null || string.IsNullOrEmpty(user.Profile.Picture))
            {
                return BadRequest("Picture is empty");
            }
            //Remove from cloudinary
            new CloudinaryService().DeleteResource(user.Profile.Picture);
            user.Profile.Picture = null;

            await _uow.SaveChangesAsync();
            return Ok("Profile picture removed successfully");
        }

Note: Entity framework was used for data storage. You can use your own persistent storage mechanism to store the images in the database.


Comments

Popular posts from this blog

Paystack In Asp.Net MVC

Sending Notification Message with Firebase with JavaScript and .Net client

Solved: Jwt Authentication in Asp.Net Web Api And Mvc