首页 文章

CakePHP,move_uploaded_file()不起作用,我没有收到任何错误

提问于
浏览
1

我想在CakePHP3中使用 move_uploaded_file() 上传文件 .

我使用了if语句来检查move_uploaded_file()返回的内容,以及false . 我附加了我的代码,但我认为我正在使用该功能 .

我的目标位置是 webroot/img/work .

我没有收到任何错误 .

我改变了主人 sudo chown www-data:www-data work/

我更改了dir权限 sudo chmod 777 work/

我是CakePHP的新手,所以我不知道还能尝试什么 .

这是我的文件:

src/Controller/WorkController.php

public function add()
    {
        // Get file to be uploaded.
        $file = $this->request->getData('image');
        // Set path to the upload location.
        $target = WWW_ROOT . 'img' . DS . 'work' . DS;

        $work = $this->Work->newEntity();
        if($this->request->is('post')) {
            $work = $this->Work->patchEntity($work, $this->request->getData());
            // Assign value.
            $work['image'] = $file['name'];
            // Move uploaded file.
            move_uploaded_file( $file['name'], $target );
            if($this->Work->save($work)) {
                $this->Flash->success(__('New work item added!'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to add new work item.'));
        }
        $this->set('work', $work );

    }

src/Template/Work/add.ctp

<?php
    echo $this->Form->create($work, array( 'enctype' => 'multipart/form-data'));
    echo $this->Form->control('title');
    echo $this->Form->control('body', ['rows' => '5']);
    echo $this->Form->control('link');
    // echo $this->Form->control('image');
    echo $this->Form->control('image', array('type' => 'file'));
    echo $this->Form->button(__('Add Work'));
    echo $this->Form->end();
?>

1 回答

  • 0

    这里给出的信息不是很多,有几点:

    根据php.net上的move_uploaded_file()

    Returns TRUE on success.
    
    If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
    
    If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.
    

    显然它不会发出警告,因此它不能是有效的上传文件 .

    查看代码,您正在尝试移动文件名 . 当您通过POST上传文件时,PHP会为其提供一个“tmp_name”,您可以通过$ file [“tmp_name”]访问该文件 .

    所以你应该做move_uploaded_file($ file [“tmp_name”],$ target);

    我假设它失败了,因为它正在寻找(myimg.png)而不是(asdagasfas.png)或任何PHP命名它 .

相关问题