Search code examples
javascripthtmlbase64summernotebase64url

Cannot load HTML code of image converted from base64 image


I have a HTML string (generated by Summernote) that contains base64 image tags. I load the image elements, convert it to image blob, upload it, and get the image-url back. Then, I set the src attribute of previous base64 image to new image-url.

When I append the image, src attribute is updated but when I log image.outerHTML, it gives back the base64 value. How can I get the image.outerHTML with update image-url?

Here is the reproduced code:

var img_string = "<img src='data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg=='/>"

var image = $(img_string);
var arr, blob, bstr, filename, mime, n, u8arr, url;

url = image.attr('src');
filename = image.attr('data-filename');
arr = url.split(',');
mime = arr[0].match(/:(.*?);/)[1];
bstr = atob(arr[1]);
n = bstr.length;
u8arr = new Uint8Array(n);
while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
}
blob = new File([u8arr], filename, {
  type: mime
});

// upload blob and get url back
var image_url = "https://images.unsplash.com/photo-1612151855475-877969f4a6cc"; //example

image.attr('src', image_url);

console.log(image); //logs image with updated src
console.log(image.prop('outerHTML')); //logs image string with base64 src
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Solution

  • Maybe the problem you're having is that you are uploading the image which is done asynchronously, and the console log is triggered before the uploading and fetching of the URL is finished. So you may try awaiting for the image to be uploaded completely using promises or the success callback if you're using jQuery.ajax and do the task only after the image has completely been uploaded.