Michael
Michael

Reputation: 79

Pass Base64 Image into ASP.net Core 3.1 Controller from View

I am trying to pass a Base64 image string sitting in a javascript variable to a controller. So far, I have been unsuccessful. I have confirmed that the string is not undefined and I think the problem lies with the AJAX I am using. My question is, How do I properly send the data to the controller?

View

<div class="col-md-4">
    <form asp-action="Create" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Title" class="control-label"></label>
            <input asp-for="Title" class="form-control" />
            <span asp-validation-for="Title" class="text-danger"></span>
        </div>
        <div class="form-group">
            <input id="ImageFile" accept="image/*">
        </div>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" id="su" />
        </div>
    </form>
</div>

To explain, I am using a 3rd party plugin for uploading images called slim cropper. This script looks for a specified input tag (in this case ImageFile) and creates an interface for users to upload pictures.

In any case, I managed to get the base 64 image from this plug-in into a variable using this java script:

...

// get a reference to the Create button
var button = document.querySelector('#submit');
var pic

// listen to clicks on the submit button
button.addEventListener('click', function () {
    alert("working")
    pic = $('.slim-area .slim-result img').attr('src');
});

...

With this done, I tried using AJAX to get this data over to the controller

...

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "/Image/Create",
    data: JSON.stringify(pic),
    dataType: "json",
    success: function (response, data) {
        alert(response.someValue);
    },
    error: function (err) {
    }
});

...

When I run the code, the model that I have setup to take the data in the controller always comes back as null. Here is very simple controller code

...

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create([FromForm] ImageModel imageModel)
    {
        return Json(new { someValue = "It's ok" });
    }

...

and Model

...

public class ImageModel
{
    [Key]
    public int ImageId { get; set; }
    [Column (TypeName="nvarchar(50)")]
    [DisplayName("Image Name")]
    public string ImageName { get; set; }
    [Column(TypeName = "nvarchar(100)")]
    public string Title { get; set; }
    [NotMapped]
    public byte[] pic { get; set; }

}

...

The eventual goal is to get these uploaded pictures into a specified folder, but before that happens, I have to pass the data in to work with. I'd appreciate any help I can get on this. Thank you for looking, and I hope I followed the posting rules correctly.

Upvotes: 1

Views: 2764

Answers (1)

Michael
Michael

Reputation: 79

As mentioned in the comments, I needed the parameter to be of type string in order for data to be passed through. Also, because the data was already in the form of a string, the JSON Stringify method wasn't needed. After these things were worked out, the program executed correctly.

Here's the final working code:

View

<div class="row">
<div class="col-md-4">
    <form asp-action="Create" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Title" class="control-label"></label>
            <input asp-for="Title" class="form-control" />
            <span asp-validation-for="Title" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="ImageFile" class="control-label">
            </label>
            <input asp-for="ImageFile" class="Form-Control" />

        </div>
        
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" id="submit" />
        </div>
    </form>
</div>

Controller

...

    public IActionResult Create ([FromBody] string pic, [Bind("ImageId, Title")] ImageModel imageModel)
    {
        var model = new ImageModel();
        var uniquefilename = Guid.NewGuid();
        var picPath = _webHostEnvironment.WebRootPath.ToString() + @"\Images\";
        var base64Data = Regex.Match(pic, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
        var binData = Convert.FromBase64String(base64Data);

        using (var imageFile = new FileStream(picPath + uniquefilename + ".png", FileMode.Create))
        {
            imageFile.Write(binData, 0, binData.Length);
            imageFile.Flush();
        }

        _context.Add(imageModel);
        return View(imageModel);
        


    }

...

Javascript

...

    // get a reference to the Create button
    var button = document.querySelector('#submit');
    //Base64 String
    var pic

    //Check for changes in picture
    var outExists;

    //set the value to look for change
    outExists = $('.slim-area .slim-result img.out').attr('src');

    // listen to clicks on the submit button
    button.addEventListener('click', function () {
        //If there is no change continue with pass orginal base64 image
        //else pass changed image
        if (outExists == null) {
            pic = "\"" + $('.slim-area .slim-result img.in').attr('src') + "\"";
        } else {
            pic = "\"" + $('.slim-area .slim-result img.out').attr('src') + "\"";
        }


        //Send base64 Image to Controller
        $.ajax({
            contentType: "application/json",
            method: "post",
            data: pic,
            success: function (response) {
                console.log("Executed...")
            },
            error: function (xhr, status, error) {
                var errorMessage = xhr.status + ': ' + xhr.statusText
                alert('Error - ' + errorMessage);
            }
        });
    });

...

Thank you to all who took a look.

Upvotes: 1

Related Questions