html上传图片并显示

因为本身就绑定了一个onchange事件,就是更换图片的时候会触发这个事件。对于FileReader我就不太懂它的工作原理是什么,懂了以后再补回来

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>显示图片</title>
    <script src="<%=request.getContextPath()%>/static/js/jquery-3.4.1.js"></script>

    <script>
        $(function () {
            clickImage()
        })
        
        function clickImage() {
            $(".image_change").change(function () {
                let item = this
                let file = this.files[0]
                let reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = function (e) {
                    console.log(this.result.length)
                    console.log(e)
                    item.nextElementSibling.setAttribute("src", this.result)
                }
            })
        }

    </script>
    <style>
        .image_upload {
            width: 134px;
            height: 134px;
            position: relative;
            border: 1px solid rgb(27, 189, 121);
        }
        .image_change {
            width: 134px;
            height: 134px;
            display: inline-block;
            opacity: 0;
            z-index: 99999;
            position: absolute;
            top: 0px;
            left: 0px;
        }
        .image_show {
            display: inline-block;
            position: absolute;
            top: 0px;
            left: 0px;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>

    <div class="image_upload">
        <input type="file" accept="image/*" class="image_change">
        <img src="" class="image_show">
    </div>
    <div class="image_upload">
        <input type="file" accept="image/*" class="image_change">
        <img src="" class="image_show">
    </div>
    <div class="image_upload">
        <input type="file" accept="image/*" class="image_change">
        <img src="" class="image_show">
    </div>
</body>
</html>
`效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021051400044932.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzE2NDQ0,size_16,color_FFFFFF,t_70#pic_center)

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值