tp(thinkphp5.1) + ajax上传图片

创作背景:

1、Jquery weui移动框架
2、用户有默认头像,上传图片判断是否是默认头像,是默认头像就不删除默认头像,非默认头像则删除原头像。
3、上传过程有个加载的动画,成功跳转个人信息,数据库存储图片地址,失败则轻提示上传失败。
4、上传的文件有要求是图片格式,并且大小不大于10M,可自行更改。

代码部分:

后台

public function set_img() {
    $file=request()->file('uploadimage');
    if(!empty($file)) {
        // 移动到框架应用根目录./static/uploads/photo目录下
        $info = $file->move('./static/uploads/photo');
        if ($info) {
            $u1 = "/static/uploads/photo/".$info->getSaveName();
            $x = Db::table('user')->where('ID',cookie('uid'))->find();
            if($x['photo'] != "/static/img/photo.png") {
                 @unlink('.'.$x['photo']);
            }
            Db::table('user')->where('ID',cookie('uid'))->update([
                'photo' => $u1,
            ]);
           return 1;
        }else return 2;
    }else return 2;
}

前台

<input id="file" name="file" class="weui-uploader__input" type="file" accept="image/*" multiple="">

Ajax 写法(jQuery)

<script>
    $(function () {
        $.toast.prototype.defaults.duration = 900;

        $("#file").on('change',function (event){
            let uploadObj = event.target.files[0];
            if(uploadObj.type.indexOf("image") == -1) {
                $("#file").val('');
                $.toast("请上传正确的图片格式!","forbidden");
            }else if(uploadObj.size > 10485760) {
                $("#file").val('');
                $.toast("请上传10M以下的图片!","forbidden");
            }else {
                var from = new FormData();
                from.append('uploadimage',uploadObj);
                $.ajax({
                    type:'post',
                    contentType: false,
                    processData: false,
                    url:'set_img',
                    data:from,
                    dataType:'json',
                    beforeSend:function () {
                        $.showLoading("更换中...");
                    },
                    success: function (data) {
                        $.hideLoading();
                        if(data == 1) {
                            $.toast("头像修改成功!");
                            setTimeout(function () {
                                window.location.href = "/index/index/login";
                            },1000);
                        }else {
                            $.toast("头像修改失败!","forbidden");
                        }
                    },
                    error: function (xhr) {
                        $.hideLoading();
                        $.toast("头像修改失败!","forbidden");
                    },
                });
            }
        });
    })
</script>

以上

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值