Laravel 圖片上傳


控制器中代碼:

    /**
     * @Name XXX
     * @Description  上傳圖片接口
     * @Param picture:圖片 @ParamTest 圖片文件
     * @apiParam   (params) {String} picture 圖片文件
     * @Response 通用格式:{"code":響應碼,"message":"錯誤描述","data":{}}
     * data{
     *    path:"圖片地址",
     * }
     *
     */

    public function uploadCompanyImg(Request $request){

        $file = $request->file('picture');
        header('Content-type: application/json');
        // 文件是否上傳成功
        if ($file->isValid()) {
            // 獲取文件相關信息
            $originalName = $file->getClientOriginalName(); //文件原名
            $ext = $file->getClientOriginalExtension();     // 擴展名

            $realPath = $file->getRealPath();   //臨時文件的絕對路徑

            $type = $file->getClientMimeType();     // image/jpeg
            $size =$file->getSize();
            $this->_result['code']=101;
            if($size > 2*1024*1024){
                $this->_result['message']='文件大小超過2M';
                echo json_encode($this->_result);
                exit();
            }
            $extArr = array('jpg','jpeg','png','gif');
            if(!in_array($ext,$extArr)){
                $this->_result['message']='文件格式不正確';
                echo json_encode($this->_result);
                exit();
            }

            // 拼接文件名稱
            $filename = date('YmdHis') . uniqid() . '.' . $ext;
            // 使用我們新建的upload_company_img本地存儲空間(目錄)
            //這里的upload_company_img是配置文件的名稱
            $bool = Storage::disk('upload_company_img')->put($filename, file_get_contents($realPath));

            if($bool){
                $this->_result['code']=200;
                $this->_result['message']='成功';
                $url='https://api.bxbedu.com/static/study/images/company/'.date('Ym',time()).'/'.$filename;
                $path='/static/study/images/company/'.date('Ym',time()).'/'.$filename;
                $this->_result['data']=array('url'=>$url,'path'=>$path);
                echo json_encode($this->_result);
            }else{
                $this->_result['message']='上傳失敗';
                echo json_encode($this->_result);
            }

        }else{
            $this->_result['message']='上傳失敗';
            echo json_encode($this->_result);
        }

    }

/config/filesystems.php的'disks' => 中添加

 'upload_company_img' => [

            'driver' => 'local',
            'url' =>  env('APP_URL').'/static',

            // 文件將上傳到storage/app/uploads目錄
            //'root' => storage_path('static/study/situation'),

            // 文件將上傳到static/study/situation目錄 如果需要瀏覽器直接訪問 請設置成這個

            'root' => public_path('static/study/images/company/'.date('Ym',time())),
        ],

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM