[SOLVED] How to get base64 img src and insert it into input.files

Issue

I have an image that is in base64. It was encoded with Convert.ToBase64String(Image) in my controller. My question is, by using JavaScript, how can I insert the already loaded image from img element into the input element so I can receive it in the controller. I think I need to decode it somehow, create a new image file and afterwards push that file in input.files, but after numerous tries I couldn’t find how. I don’t have a lot of experience in javascript, so I would appreciate it if someone helps me out.

<img id="mainImage" src="data:image;base64,@Model.ImageInBase64">

<input asp-for="Image" id="mainImageInput" style="display:none" type="file" onchange="readURL(this,'mainImage')" accept="image/jpeg, image/png" class="form-control"/>

My view model has these 2 properties:

    [Required]
    public IFormFile Image { get; set; }
    public string? ImageInBase64 { get; set; }

For more context, I am saving all my images in a database as byte[].

Solution

You need convert base64 image to file, then use DataTransfer to recivie the file. You can try my sample code like below.

@{
    ViewData["Title"] = "Home Page";
}
@model Net5_MVC.Controllers.HomeController.mainImageInput
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script>
    function dataURLtoFile(dataurl, filename) {

        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);

        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }

        return new File([u8arr], filename, { type: mime });
    }
    function ConvertClick(base64url) {
        var file = dataURLtoFile(base64url, "test.png");
        let container = new DataTransfer();
        container.items.add(file);
        document.querySelector('#mainImageInput').files = container.files;
        var newfile = document.querySelector('#mainImageInput').files[0];
    }
</script>

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<img id="mainImage" style="width:200px;height:160px" src="@Model.ImageInBase64">

<input asp-for="Image" id="mainImageInput" style="display:none" type="file" accept="image/jpeg, image/png" class="form-control" />
<button onclick="ConvertClick('@Model.ImageInBase64')">Convert</button>

Test Result:

enter image description here

Answered By – Jason Pan

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *