tp5.0图片上传

时间:2022-10-17 00:19:51
 public function upload_file() {
        try {
            $this->regapi([
                'f_server_name' => '外部调用-上传图片',
                'f_server_url' => 'xxxx/frame/apis/upload_file',
                'f_server_code_type' => '1',
                'f_server_port' => '80',
            ]);

            //获取上传文件信息;
            $files = request()->file('image');
            if (empty($files)) {
                $e = new apis_exception();
                $e->seterror(607);
                throw  $e;
            }
            $filePaths = ROOT_PATH . 'public' . DS . 'uploads';
            if (!file_exists($filePaths)) {
                mkdir($filePaths, 0777);
            }
            foreach($files as $file){
                $info = $file->move($filePaths);
                if (empty($info)) {
                    $e = new apis_exception();
                    $e->seterror(606);
                    throw  $e;
                }
                $imgpath = ROOT_PATH . 'public' . DS . 'uploads/' . $info->getSaveName();
                $image = \think\Image::open($imgpath);
                $date_path = ROOT_PATH . 'public' . DS . 'uploads';
                if (!file_exists($date_path)) {
                    mkdir($date_path, 0777, true);
                }
                $thumb_path = $date_path . '/' . $info->getFilename();
                $image->thumb(120, 120)->save($thumb_path);
                
                $path = toolapp::toolOss($dir, $imgpath);
                $smallPath = toolapp::toolOss($dir, $thumb_path);
                if(empty($path) ||empty($smallPath)){
                    $e = new apis_exception();
                    $e->seterror(605);
                    throw  $e;
                }
                //数据入库;
                $data = [
                    'f_image_path' => $path['url'],//上传原图
                    'f_small_image_path' => $smallPath['url'],//上传缩略图
                    'f_image_add_time' => time(),        //添加时间
                    'f_image_up_time' => time(),        //更新时间
                    'f_image_add_operator' => $this->php->common_user->get_uid(),//操作人
                ];
                //返回给前端数据;
                $arr=[
                     'image'=>$path['url'],
                     'thumb'=>$smallPath['url'],
                ];
                unset($info);//清除文件,非常重要;
                @unlink($thumb_path);
                @unlink($imgpath);//删除文件
                rmdir('uploads/' . date('Ymd', time()));//删除文件夹
                $image_info[]=$data;
                $arr2[]=$arr;
            }

            //批量插入数据库;
            Db::name(dn::image_image)->insertAll($image_info);
            //返回数据;
            return [
                'status' => true,
                'msg' => '上传成功!',
                'data' => $arr2
            ];
        }catch (appexception $e) {
            $e->handle();
        }
    }