2

Trying to insert an image inside a div, between lorem and ipsum:

$('#inpfile').on('change', function(){
 var img = $(this).prop('files')[0];
 document.execCommand('insertImage', img);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='file' id='inpfile' accept="image/jpeg, image/png, image/gif">
<br><br>
<div contenteditable>
lorem ipsum
</div>

Nothing happens. Any help?

qadenza
  • 9,025
  • 18
  • 73
  • 126
  • "_[insertImage] requires a URL string for the image's src_" See https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand `$(this).prop('files')[0]` is an object, not an URL string. – Teemu Mar 13 '19 at 08:26
  • @Teemu, how to get the `URL string`? There is no a word on the link. – qadenza Mar 13 '19 at 08:29
  • 1
    [e.g.](https://stackoverflow.com/a/22245534/1169519). – Teemu Mar 13 '19 at 08:33

2 Answers2

2

insertImage requires an image URL and you are passing a file object. Your code actually inserts an <img> tag but without src attribute, which is why you don't see it.

You can retrieve image URL with a FileReader. Here is a working code for what you want to achieve:

$('#inpfile').on('change', function(){
    var file = $(this).prop('files')[0];
    var reader  = new FileReader();

    reader.addEventListener("load", function () {
        document.execCommand('insertImage', false, reader.result);
    }, false);

    if (file)
        reader.readAsDataURL(file);
});
  • it works, thanks a lot. Could you pls a bit explain this - `if (file) reader.readAsDataURL(file);` – qadenza Mar 13 '19 at 08:34
  • 1
    This line reads your file object and converts it to a raw data URL (which you retrieve in the "load" event listener declared above). The "if (file)" is just there to ensure you actually selected a file. – Timothé Malahieude Mar 13 '19 at 08:37
0

I think my solution should have better readability:

<input type='file' id='inpfile' accept="image/jpeg, image/png, image/gif">
<br><br>
<div id="target">
    lorem ipsum
</div>
<script>
   $( document ).ready(function(){
      $('#inpfile').on('change', function(){
         var targetDiv=document.getElementById("target");
         var file = $(this).prop('files')[0];
         var img=document.createElement("img");
         var reader  = new FileReader();
         targetDiv.append(img);
         reader.addEventListener("load", function () {
            img.src=reader.result;
         }); 
         if (file)
            reader.readAsDataURL(file);
        });
   })
</script>
The KNVB
  • 3,588
  • 3
  • 29
  • 54