📜  蛋糕中的图片上传 2 - PHP 代码示例

📅  最后修改于: 2022-03-11 14:54:50.807000             🧑  作者: Mango

代码示例2
public function add() {
    if ($this->request->is('post')) {
        $this->Category->create();
        //Check if image has been uploaded
        if (!empty($this->request->data['Category']['upload']['name'])) {
            $file = $this->request->data['Category']['upload'];

            $ext = substr(strtolower(strrchr($file['name'], '.')), 1);
            $arr_ext = array('jpg', 'jpeg', 'gif','png');

            if (in_array($ext, $arr_ext)) {
                move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/webimages/categories/' . $file['name']);
                //prepare the filename for database entry
                $this->request->data['Category']['image'] = $file['name'];
            }
        }

        if ($this->Category->save($this->request->data)) {
            $this->Session->setFlash(__('The category has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The category could not be saved. Please, try again.'));
        }
    }
    $parentCategories = $this->Category->ParentCategory->find('list');
    $categoriesStatus = $this->Category->getCategoriesStatus();//model's method to get list of status
    $this->set(compact('parentCategories', 'categoriesStatus'));
}