Simple implementation of image upload preview

Realize the upload preview of the picture:

  Before the company's business needs, I found a lot of examples of implementing image uploading and preview, but found that they are not very easy to use, and it is more troublesome. Later, a colleague recommended a method, which is relatively simple and functional. Not much to say, go directly to the code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<input type="file" id="img" />
<div id="div"></div>
</body>
<script>
    var reader = new FileReader();
    var img = document.getElementById("img");
    var div = document.getElementById("div");
    img.onchange = function() {
        var file = img.files[0];
        reader.readAsDataURL(file);
        reader.onload = function() {
            div.innerHTML = "<img src = '" + this.result + "' />"
        }
    }
</script>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325253680&siteId=291194637