js上传图片代码实现

这段代码展示了如何使用JavaScript实现点击按钮后打开文件选择框,选择图片后进行上传,并更新页面上的头像显示。它利用了FormData对象和Ajax进行异步文件上传,同时提供了上传成功后的回调处理,包括更新头像URL和设置用户头像字段。
摘要由CSDN通过智能技术生成

在这里插入图片描述


 <div class="edit-avatar">
                        <img src="${ (user.userAvatar) !}" alt="..." class="img-avatar">
                        <div class="avatar-divider"></div>
                        <div class="edit-avatar-content">


                              <button class="btn btn-default"  id="change_avatar">修改头像
                                 </button>

                            <input type="file" id="_avatar_file" name="file" class="hidden" />

                            <p class="m-0">选择一张你喜欢的图片,裁剪后会自动生成264x264大小,上传图片大小不能超过2M。</p>
                        </div>
                    </div>



$('#change_avatar').click(function (e) {
    console.log('点击了')
    $('#_avatar_file').click()
})
const imgAvatar = $('.img-avatar');
$('#_avatar_file').change(function () {
    //input 隐藏域 收到后 自动触发上传
    const data = new FormData();
    data.append('file',_val('#_avatar_file'))
    _$_ajax_formData({
        url:'/api/file',
        data: data,
        success: function (res) {
            if (res.code==200) {
                console.log(res)
                _successInfo()
                imgAvatar.attr('src',res.data.url+'?@64h_64w_1e')
                _set_name_val('userAvatar',res.data.url)
            }else{
                _errorInfo()
            }
        },
        error: function (res) {
            _errorInfo()
        }
    })
})

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值