-2

So the problem is that I want to create an img element with the same src as the insert file but its not working and I dont know why, here is the code:

<!DOCTYPE html>
<html>
<head>
<title>HMM...</title>
</head>
<body>
<input type="file" id="wowo">
<div id="dispImg">
</div>
<button onclick="wp()">run</button>
<script>
window.URL = window.URL || window.webkitURL;
function wp() {
var file = document.getElementById("wowo").value;

var nopath = file.substring(12);
alert(nopath);

var crimg = document.createElement("img");
crimg.src = window.URL.createObjectURL(nopath);
crimg.height = 60;
crimg.onload = function() {
window.URL.revokeObjectURL(this.src);
}
document.getElementById("dispImg").appendChild(crimg);
}
</script>
</body>
</html>

Thank you.

  • Possible duplicate of [Preview an image before it is uploaded](https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded) – James Coyle Apr 09 '19 at 10:47

1 Answers1

1

You can try this code:

function wp() {
   var files = document.getElementById("wowo").files;

   // FileReader support
   if (FileReader && files && files.length) {
       var crimg = document.createElement("img");
       var fr = new FileReader();
       fr.onload = function () {
           crimg.src = fr.result;
       }
       fr.readAsDataURL(files[0]);
       crimg.height = 60;

       document.getElementById("dispImg").appendChild(crimg);
     }
  }

This is a demo https://jsbin.com/qaqoveq

Ryan Nghiem
  • 2,212
  • 1
  • 13
  • 23