Click here to Skip to main content
15,885,767 members
Articles / Web Development / HTML
Tip/Trick

ASP.NET MVC 5 Multiple Image Uploader with Crop

Rate me:
Please Sign up or sign in to vote.
4.67/5 (16 votes)
15 Apr 2015CPOL1 min read 39.9K   2.2K   30   16
ASP.NET MVC 5 Multiple Image Uploader with Crop

Introduction

The standard input with type file allows us to upload files. One of the usually uploaded file types is images. And it is very useful when you can preview images before upload and moreover define certain area of image that should be uploaded. Here, I will demonstrate how to create multi image uploader with crop using ASP.NET MVC.

Background

To help us preview images and apply crop, I will use my own jQuery plugin jquery.multiuploader.crop.js which will do all UI work for us.

Using the Code

To create UI for uploader, simply define div element in your markup and apply plugin jquery.multiuploader.crop.js to it like so:

JavaScript
$('#myUploader').imageUploaderCut({
                proceedCallBack: uploadCallBack
                });

The UI part will only return Json with array of objects as parameter to call back function. Each object will contain necessary information to upload the cropped image.

JavaScript
var o = {
    'Content': img.attr('src'),
    'FileName': aperture.attr('data-filename'),
    'ContentLenght': aperture.attr('data-filesize'),
    'ImgWidth': img.width(),
    'ImgHeight': img.height(),
    'CropX': Math.abs(parseInt(img.css('left'))),
    'CropY': Math.abs(parseInt(img.css('top'))),
    'CropWidth': aperture.width(),
    'CropHeight': aperture.height()
};

And .NET model:

C#
public class UploadFileModel {
        public string Content { get; set; }
        public string FileName { get; set; }
        public int ContentLenght { get; set; }
        public float ImgWidth { get; set; }
        public float ImgHeight { get; set; }
        public float CropX { get; set; }
        public float CropY { get; set; }
        public int CropWidth { get; set; }
        public int CropHeight { get; set; }
    }

Once all manipulation with images are done and we ready to post data to server, we will use this code:

JavaScript
function uploadCallBack(jsonString) {
    $.ajax({
            url: '/Home/UploadToServer',
            type: 'POST',
            dataType: 'json',
            data: jsonString,
            contentType: 'application/json; charset=utf-8',
            success: function(data, event) {
                //do redirect
            },
            error: function (data, event) {
                //do redirect
            }
        });
    }

On the server side, we will define action which accepts list of uploaded images:

C#
[HttpPost]
[JsonFilter( Param = "widgets", JsonDataType = typeof (List<UploadFileModel>) )]
public JsonResult UploadToServer( List<UploadFileModel> images )

Here, you can see custom attribute with the help of which I deserialize Json to Model object.

C#
public class JsonFilter : ActionFilterAttribute {
  public string Param { get; set; }
  public Type JsonDataType { get; set; }
  public override void OnActionExecuting( ActionExecutingContext filterContext ) {
       string inputContent;
       filterContext.HttpContext.Request.InputStream.Position = 0;
       using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream)) {
           inputContent = sr.ReadToEnd();
       }
       var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
       filterContext.ActionParameters[Param] = result;
  }
}

Download the attached source code to see how exactly I've done crop and save cropped images.

Points of Interest

While creating this sample uploader, I dug a little bit into school course of geometry to learn how to properly resize image and keep the ratio between width and height.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to Change the Resolution from 300x300 to 512x512 Pin
L30P1N04-Feb-17 7:23
L30P1N04-Feb-17 7:23 
AnswerRe: How to Change the Resolution from 300x300 to 512x512 Pin
Mikhail Vasilchenko7-May-17 0:02
Mikhail Vasilchenko7-May-17 0:02 
QuestionImage file size problem Pin
Member 1089354021-Jul-16 2:05
Member 1089354021-Jul-16 2:05 
AnswerRe: Image file size problem Pin
Mikhail Vasilchenko25-Jul-16 0:21
Mikhail Vasilchenko25-Jul-16 0:21 
QuestionShow how to Crop Image Pin
Ron Yam26-Feb-16 10:34
Ron Yam26-Feb-16 10:34 
AnswerRe: Show how to Crop Image Pin
Mikhail Vasilchenko27-Feb-16 6:41
Mikhail Vasilchenko27-Feb-16 6:41 
QuestionAwesome Pin
Member 117993139-Sep-15 3:27
Member 117993139-Sep-15 3:27 
QuestionShared the source code Pin
Mikhail Vasilchenko16-Apr-15 22:37
Mikhail Vasilchenko16-Apr-15 22:37 
AnswerRe: Shared the source code Pin
Hanumantha reddy GS17-Apr-15 1:34
Hanumantha reddy GS17-Apr-15 1:34 
GeneralRe: Shared the source code Pin
Mikhail Vasilchenko17-Apr-15 1:59
Mikhail Vasilchenko17-Apr-15 1:59 
QuestionWhere is the download link??? Pin
Bh@vesh16-Apr-15 15:22
Bh@vesh16-Apr-15 15:22 
AnswerRe: Where is the download link??? Pin
Mikhail Vasilchenko16-Apr-15 22:37
Mikhail Vasilchenko16-Apr-15 22:37 
QuestionWhere is the download link? Pin
Hanumantha reddy GS15-Apr-15 8:15
Hanumantha reddy GS15-Apr-15 8:15 
AnswerRe: Where is the download link? Pin
Mikhail Vasilchenko16-Apr-15 22:38
Mikhail Vasilchenko16-Apr-15 22:38 
QuestionShare the code Pin
Hanumantha reddy GS15-Apr-15 6:29
Hanumantha reddy GS15-Apr-15 6:29 
AnswerRe: Share the code Pin
Mikhail Vasilchenko16-Apr-15 22:38
Mikhail Vasilchenko16-Apr-15 22:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.