Search code examples
asp.net-mvc.net-coresummernote

Summernote image upload with .NET Core


Im really struggling to get SummerNote to upload an iamge in .NET core. The trouble is the IFormFile file parameter is null when a new image is uploaded.

I initialise Summernote using the following -

$('#MessageBody').summernote({
    height: ($(window).height() - 300),
    callbacks: {
        onImageUpload: function(image) {
            uploadImage(image[0]);  
        }
    }
});

Here is the uploadImage function -

function uploadImage(image) {
    var data = new FormData();
    data.append("image", image);
        $.ajax({
            url: '/EmailTemplate/UploadImage',
            cache: false,
            contentType: false,
            processData: false,
            data: data,
            type: "post",
            success: function(url) {
                var image = $('<img>').attr('src', 'http://' + url);
                $('#MessageBody').summernote("insertNode", image[0]);
                
                alert(url);  
                var imgNode = document.createElement('img');  
                imgNode.src = url;  
                $('#MessageBody').summernote('insertNode', imgNode);  
            },
            error: function(data) {
                console.log(data);
            }
    });

And finally, here is the controller -

[HttpPost]
    public async Task<IActionResult> UploadImage(IFormFile file)
    {
        string message;
        var saveimg = Path.Combine(_hostingEnvironment.WebRootPath, "Images", file.FileName);
        string imgext = Path.GetExtension(file.FileName);

        if (imgext == ".jpg" || imgext == ".png")
        {
            using (var uploadimg = new FileStream(saveimg, FileMode.Create))
            {

                await file.CopyToAsync(uploadimg);
                message = "The selected file" + file.FileName + " is saved";
            }

        }
        else
        {
            message = "only JPG and PNG extensions are supported";
        }
        // return "filename : " + saveimg + " message :" + message; 
        
        return Content(Url.Content(saveimg));
    }

Solution

  • The parameter is called file while the field name is image. To fix this use the same name, either file or image.

    The IFormFile type represents the value of an input type=file field. IFormFile parameters are bound to fields based on their name. There may be many file fields in the same form so the type isn't enough to determine the field.

    Field binding is explained in the Sources section of the Model Binding document.