首页 > 代码库 > 上传图片-简易

上传图片-简易

                                    <div class="col-sm-3">
                                        <div class="imguploadbox">
                                                <label for="imgUpload">
                                                <input type="file" id="imgUpload" accept=".png,.jpg" style="display: none">
                                            </label>
                                            <div class="addimg">
                                                <?php if($model->thumb): ?>
                                                    <img src="http://www.mamicode.com/<?= $model->thumb ?>_120X120.png" class="img-circle" id="user_img"">
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-9">
                                        <div class="editavatarcontrol" style="margin-left:25px;">
                                            <p>支持格式:JPEG / PNG 512X512, < 1MB</p>
                                            <button type="button" class="btn btn-avatar" id="image-change-btn">修改图片</button>
                                        </div>
                                    </div>

  

  $(‘#imgUpload‘).on(‘change‘,function(){
            imgUpload();
    });

    function imgUpload(){
        var formdata = new FormData();
        formdata.append(‘UploadForm[imageFile]‘,$(‘#imgUpload‘)[0].files[0]);
        $.ajax({
            url:‘/site/upload‘,
            type: ‘post‘,
            cache:false,
            data: formdata,
            processData:false,
            contentType:false,
            success:function(data){
                if(data === ‘error‘){
                    $.confirm({
                        title : ‘提示‘,
                        content : ‘图片大小格式不符,请选择合适图片‘,
                        buttons : {
                            confirm : {
                                text : ‘确认‘
                            }
                        }
                    })
                }else{
                var tempImg = $(‘<img/>‘);
                tempImg.attr(‘src‘,data+‘_120X120.png‘);
                tempImg.attr(‘width‘,‘120‘);
                tempImg.attr(‘height‘,‘120‘);
                $(‘#user_img‘).remove();
                $(‘.addimg‘).empty().append(tempImg);
                window.location.reload();
                }
            },
            error:function(e){

                $.confirm({
                    title: ‘提示‘,
                    content: ‘头像上传遇到错误,请检查图片‘,
                    buttons: {
                        confirm: {
                            text: ‘确认‘
                        }
                    }
                })
            }
        })
    }
    $(‘#image-change-btn‘).click(function(){
        $(‘#imgUpload‘).click();
    })

  

上传图片-简易