tp5 上傳圖片(自定義圖片路徑)


控制器調用

        /**
         * [goods_addimg 圖片上傳]
         * @return [type] [description]
         */
        public function addimg(){
            if (request()->isPost()) {
                $post = request()->file();
                $str = '';
                $d = "";
                $i = 0;
                //自定義路徑
                $url = 'img' . DS . 'goodsimg';
                foreach ($post as $key => $value) {
                    $i++;
                    if ($i!=1) {
                        $d = ",";
                    }
                    $str .= $d.  addimg($value,$url);
                }
                return jsonData(1,'圖片上傳成功',$str);
            }
        }    

 

 

公共方法

/**
 * [addimg 圖片上傳]
 * @param  [type] $filename [description]
 * @return [type]           [description]
 */
function addimg($pic,$url){

    // 獲取表單上傳文件 例如上傳了001.jpg
    // $file = request()->file($filename);
    // 移動到框架應用根目錄/public/uploads/ 目錄下
    // $file = request()->file($pic);
    if (is_array($pic)) {

        foreach($pic as $file){
            // 'img' . DS . 'goodsimg'
            // 移動到框架應用根目錄/public/uploads/ 目錄下
            $info = $file->validate(['size'=> 1024 * 1000 ,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public'. DS .$url);
            $data[] = str_replace('\\', '/',$url . '/' . $info->getSaveName());
        }

        return implode(',',$data);
    } elseif (is_object($pic)) {
        $info = $pic->validate(['size'=> 1024 * 1000 ,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public'. DS . $url);
        if($info){
            //返回文件位置信息 如:20180620/42a79759f284b767dfcb2a0197904287.jpg
            return  str_replace('\\', '/',$url . '/' . $info->getSaveName());

        }else{
            // 上傳失敗獲取錯誤信息
            return false;
            // return $file->getError();
        }
        //單文件上傳
    }
}

 


免責聲明!

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



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