头像上传预览

点击头像实现头像上传预览

前端代码

<style>
    #addImgDiv{
        width: 64px;
        height: 64px;
        float: left;
        border-radius: 50%;
        border: 3px solid #eee;
        overflow: hidden;
        background-image: url("/img/userImgs/defUser.jpg");
        background-size: cover;
        text-align: center;
    }
</style>
<body>
<form action="/addPic" method="post"  role="form" enctype="multipart/form-data">
    <div class="input-field col s12" style="padding-left: 38%">
        <div  id="addImgDiv">
            <input id="addImg" name="img"  type="file" style="opacity: 0;width: 64px;height: 64px" accept=".jpg,.png,.gif"/>
        </div>
    </div>
</form>
<script>
    $("#addImg").change(function () {
        var img=$("#addImg")[0].files
        var file=img[0];
        console.log(img);
        console.log(file)
        var URL = window.URL || window.webkitURL;
        // 通过 file 生成目标 url
        var imgURL = URL.createObjectURL(file);
        // 用这个 URL 产生一个 <img> 将其显示出来
        $("#addImgDiv").css("background-image","url("+imgURL+")");
        console.log(imgURL)
    });
</script>

后台代码:

 @RequestMapping(value = "/addPic")
    public String addUser(HttpServletRequest request, @RequestPart("img") MultipartFile picture) throws IOException {

        String filename = picture.getOriginalFilename();
        String realPath = request.getServletContext().getRealPath("/img");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0,9);
        //默认选择defUser.jpg
        String imgPath=realPath+"/userImgs/defUser.jpg";
        //没有选择默认头像。。。。
        if (!("".equals(filename)||filename==null)){
            imgPath=realPath+"/userImgs/"+uuid+filename;
        }
        picture.transferTo(new File(imgPath));
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值