\ Zend \ File \ Transfer \ Adapter \ Http()和filerenameupload

时间:2014-03-19 09:03:16

标签: php file-upload zend-framework2

我正在尝试将'filerenameupload'过滤器与\ Zend \ File \ Transfer \ Adapter \ Http()一起使用:

    $adapter = new \Zend\File\Transfer\Adapter\Http();

    $adapter->addFilter('filerenameupload', array(
        'target' => BASE_DIR . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR .
        'img' . DIRECTORY_SEPARATOR . 'gallery' .
        DIRECTORY_SEPARATOR . 'image.jpg',
        'randomize' => true,
    ));

    var_dump($adapter->isValid()); // true

    if (!$adapter->receive()) {
        $messages = $adapter->getMessages();
        echo implode("\n", $messages);
    }

始终有错误,

  

无法重命名文件'/tmp/somefile.png'。处理文件时发生错误。

/tmp/somefile.png - 存在,可读,可写,扩展文件夹也可读写

错误来自RenameUpload类:

protected function moveUploadedFile($sourceFile, $targetFile)
{
    ErrorHandler::start();
    $result = move_uploaded_file($sourceFile, $targetFile);
    $warningException = ErrorHandler::stop();
    if (!$result || null !== $warningException) {
        throw new Exception\RuntimeException(
        sprintf("File '%s' could not be renamed. An error occurred while processing the file.", $sourceFile), 0, $warningException
        );
    }

    return $result;
}

所以也许有人有一个例子或知道如何解决这个错误?或者我做错了什么?

1 个答案:

答案 0 :(得分:1)

感谢来自#zftalk的@hemangpatel的建议,所以工作行为如下:

public function uploadAction()
{
    $adapter = new \Zend\File\Transfer\Adapter\Http();

    $adapter->setDestination(BASE_DIR . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR .
            'img' . DIRECTORY_SEPARATOR . 'gallery' . DIRECTORY_SEPARATOR);
    // Returns all known internal file information

    $adapter->addFilter('File\Rename', array('target' => $adapter->getDestination() .
        DIRECTORY_SEPARATOR . rand(2, 10) . '.jpeg',
        'overwrite' => true));

    if (!$adapter->receive()) {
        $messages = $adapter->getMessages();
        return new ViewModel(['messages' => $messages]);
    } else {
        $this->flashMessenger()->addSuccessMessage('Upload success');

        $this->redirect()->toRoute('admin', ['controller' => 'gallery',
            'action' => 'index']);
    }
}