Загрузка файла в Cakephp 3.3

Я пытаюсь сохранить изображение в cakephp 3.0. Я могу только сохранить имя файла в db, однако не могу сохранить фактический файл на сервере. Нужна помощь

Форма:

        echo $this->Form->create('User', array('url' => array('action' => 'create'), 'enctype' => 'multipart/form-data'));
        echo $this->Form->input('upload', array('type' => 'file'));

Контроллер изображений:

 */
public function add()
{
    $image = $this->Images->newEntity();
    //Check if image has been uploaded
    if(!empty($this->request->data['Images']['upload']['name']))
    {
        $file = $this->request->data['Images']['upload']; //put the data into a var for easy use

        $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
        $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

        //only process if the extension is valid
        if(in_array($ext, $arr_ext))
        {
            //do the actual uploading of the file. First arg is the tmp name, second arg is
            //where we are putting it
            move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img' . $file['name']);

            //prepare the filename for database entry
            $this->data['Images']['image'] = $file['name'];
        }
    }

    if ($this->request->is('post')) {
        $image = $this->Images->patchEntity($image, $this->request->data);
        if ($this->Images->save($image)) {
            $this->Flash->success('The image has been saved.');
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error('The image could not be saved. Please, try again.');
        }
    }
    $this->set(compact('image'));
    $this->set('_serialize', ['image']);
}

person amalik14    schedule 29.04.2015    source источник


Ответы (2)


Добро пожаловать в stackoverflow!

Пожалуйста, проверьте этот вопрос: cakePHP 3.0 загружает изображения

Это поможет вам, это хороший плагин для загрузки изображений: http://cakemanager.org/docs/utils/1.0/behaviors/uploadable/

person Gilko    schedule 29.04.2015
comment
Этот URL-адрес подвергся вирусной атаке... пожалуйста, не открывайте другие - person Mithilesh Kumar; 12.10.2018

Для тех, кто ищет ответ, просто измените эту строку:

move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img' .DS. $file['name']);

DS — это разделитель каталогов.

person Hanane    schedule 26.01.2016