0

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[].

Nikola Develops
  • 151
  • 3
  • 12
  • Follow this. May work for you [https://stackoverflow.com/questions/21227078/convert-base64-to-image-in-javascript-jquery](https://stackoverflow.com/questions/21227078/convert-base64-to-image-in-javascript-jquery) – Tayfun Yuksel Mar 14 '22 at 11:28
  • 1
    _"It was encoded ... in my controller"_, _"so I can receive it in the controller"_ - Why the round-trip when the image is already on the server? – Andreas Mar 14 '22 at 11:28
  • 1) you can base64 the image on the client side using JS, so that you save a needless round-trip to your server 2) why put the base64 string back in to a `file` input? Just send it as a string and let the server handle the file transform. – Rory McCrossan Mar 14 '22 at 11:30
  • 1) I had that idea as well but as I said I am not very familiar with java script so instead I did what I could, if you can provide any tips I would appreciate it :) 2) it's because the image file is required (this code is used for upload image functionality where users make advertisements and have the ability to edit them, but the first primary image is required always, ). Here is the github repository - https://github.com/nikoladevelops/Marketplace . Feel free to explore and give me more tips, I like your second point too, but that would require some extra logic for validating my view model. – Nikola Develops Mar 14 '22 at 12:09

2 Answers2

1

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://learn.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

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
0

I'm not sure if I understand you correctly. But you can decode Base64 back to the input by using

const reader = new FileReader();  
 ​    reader.onload = (evt) => {  
 ​        setFile(evt.target.result);  
 ​    }
reader.readAsDataURL(base64_here'));

 

​    

Dave
  • 3,073
  • 7
  • 20
  • 33