前端图片上传预览

前端图片上传预览

方法一: (jq)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>input-img</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
    <style>
        img {
            width: 100px;
            height: auto;
        }

    </style>
</head>
<body>
    <div class="imgBox"></div>
    <!-- accept: 规定文件类型
    multiple: 允许多文件上传 -->
    <input type="file" name="file" id="file" class="file" accept="image/jpg,image/jpeg,image/png,image/bmp" multiple>
</body>
    <script>
        $(function () {
            $('#file').change(function () {
                var imgArr = []; //获取的图片地址
                var fileList = $(this)[0].files;   //或获取的图片文件
                console.log(fileList);
                var Length = fileList.length;
                for ( var i = 0; i < Length; i++ ) {
                    var imgUrl = window.URL.createObjectURL(fileList[i]); //获取图片地址
                    imgArr.push(imgUrl);
                    console.log(imgArr);
                    var $img = $("<img class='img'>");
                    $('.imgBox').append($img);
                    $img.attr('src', imgArr[i]);
                }
            });
        })
    </script>
</html>

效果图:

 

方法二: 

<!doctype html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <input type="file"><br>
        <img src="" height="200" alt="Image preview area..." title="preview-img">
        <script>
            var fileInput = document.querySelector('input[type=file]'),
                previewImg = document.querySelector('img');
            fileInput.addEventListener('change', function() {
                var file = this.files[0];
                var reader = new FileReader();
                // 监听reader对象的的onload事件,当图片加载完成时,把base64编码賦值给预览图片
                reader.addEventListener("load", function() {
                    previewImg.src = reader.result;
                }, false);
                // 调用reader.readAsDataURL()方法,把图片转成base64
                reader.readAsDataURL(file);
            }, false);
        </script>
    </body>
</html>

 

posted on 2017-11-03 15:16  梦幻飞雪  阅读(1976)  评论(0编辑  收藏  举报