天天看點

web前端-上傳圖檔預覽

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>圖檔上傳預覽</title>
    <style>
        .pop .upload {
            position: relative;
            background: url('../images/pop-tjtp.png') no-repeat;
            width: 242px;
            height: 242px;
            margin: 0 auto;
            overflow: hidden;
        }

        .pop .upload input {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
        }

        .pop .upload img {
            display: block;
            width: 242px;
            height: 242px;
            box-sizing: border-box;
            border: 1px solid #ecc6b5;
        }
    </style>
</head>

<body>
    <!-- 上傳圖檔 -->
    <div class="pop">
        <div class="upload">
            <img id="img">
            <input type="file" onchange="showImg(this)">
        </div>
    </div>

    <!-- js部分 -->
    <script src="./package/jquery-1.9.1.min.js"></script>
    <script>
        function showImg(obj) {
            var file = $(obj)[0].files[0]; //擷取檔案資訊
            var imgdata = '';
            if (file) {
                var reader = new FileReader(); //調用FileReader
                reader.readAsDataURL(file); //将檔案讀取為 DataURL(base64)
                reader.onload = function (evt) { //讀取操作完成時觸發。
                    $("#img").attr('src', evt.target.result) //将img标簽的src綁定為DataURL
                };
            } else {
                alert("上傳失敗");
            }
        }
    </script>
</body>

</html>
           

點選/觸摸:

web前端-上傳圖檔預覽

效果:

web前端-上傳圖檔預覽

Yozo撒花

繼續閱讀