图片/头像上传通用方法

if($_FILES["file"]["error"]!==1)
{
    return redirect()->route("change_password")->with("msg","头像上传出错 错误码:".$_FILES["file"]["error"]);
}
else
{
    //没有出错
    //加限制条件
    //判断上传文件类型为png或jpg且大小不超过1024000B
    if(($_FILES["file"]["type"]=="image/png"||$_FILES["file"]["type"]=="image/jpeg")&&$_FILES["file"]["size"]<1024000)
    {
        //地址文件名拼接
        $type=explode(".",$_FILES["file"]["name"]);
        $filename ="./upload/".$user_id.'-'.date('YmdHis',time()).mt_rand(1000,9999).'.'.$type[1];
        //转码,把utf-8转成gb2312,返回转换后的字符串, 或者在失败时返回 FALSE。
        $filename =iconv("UTF-8","gb2312",$filename);
        //检查文件或目录是否存在
        if(file_exists($filename))
        {
            return redirect()->route("change_password")->with("msg","图片已存在");
        }
        else
        {
            $dir = './upload';
            is_dir($dir) OR mkdir($dir, 0777, true);
            //保存文件,   move_uploaded_file 将上传的文件移动到新位置
            move_uploaded_file($_FILES["file"]["tmp_name"],$filename);//将临时地址移动到指定地址
            if($staff['image']!=null){
                if(file_exists($staff['image'])){
                    unlink($staff['image']);
                }
            }
            $staff->image=$filename;
            if($staff->save()){
                return redirect()->route("change_password")->with("msg","头像上传成功");
            }
        }
    }
    else
    {
        return redirect()->route("change_password")->with("msg","图片类型只能为JPG或PNG,且大小不能超过1M");
    }
}

转载于:https://my.oschina.net/guozhouyuan/blog/1935898

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值