js + files target to achieve a simple image upload preview

Image upload preview effect

js + files target to achieve a simple image upload preview

Step by step to optimize, from a simple beginning, come on!

  1. Use to access files in the picture, and use the change event to listen for file uploads
  2. Gets file objects
  3. Analysis target, turn into object base64 url

image: ![Alt](https://avatar.csdn.net/7/7/B/1_ralf_hx163com.jpg

code show as below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="file" id="imgObj" onchange="getImage()"/>
    <img src="" id="imgId"/>
    <script>
        getImage= function(){
             //1:获取file对象
            var upImage = document.getElementById('imgObj');
            var objImage = upImage.files[0];
            var reader = new FileReader();
             //2:解析对象,转成baae64对象的url
            reader.addEventListener("load", function () {
                var imgurl = reader.result;
                 var imgId = document.getElementById('imgId');
                 imgId.src=imgurl;
            }, false);

             if (objImage) {
                 //在load中返回一个base64编码
                reader.readAsDataURL(objImage);
            }
        };
    </script>
</body>
</html>


Published 11 original articles · won praise 1 · views 1167

Guess you like

Origin blog.csdn.net/u014403513/article/details/88412051