Search code examples
zend-framework2

File upload ZF2


Is there an obvious reason as to why there is no file being crated in ./data/stockhelper. The permissions are correct.

public function uploadAction()
{

    $request = $this->getRequest();

    if($request->isPost()) {

        $files =  $request->getFiles()->toArray();

        $httpadapter = new \Zend\File\Transfer\Adapter\Http();
        $filesize  = new \Zend\Validator\File\Size(array('max' => 100000 )); //1KB
        $extension = new \Zend\Validator\File\Extension(array('extension' => array('xlsx')));

        $httpadapter->setValidators(array($filesize, $extension), $files['file']['name']);
        if($httpadapter->isValid()) {
            // We get here.

// move_uploaded_file($_FILES['file']['tmp_name'], sprintf('./data/stockhelper/%s.%s', sha1_file($_FILES['file']['tmp_name']), 'xlsx')); // <--- this works


            $httpadapter->setDestination('./data/stockhelper');
            if($httpadapter->receive($files['file']['name'])) {
                // We don't get here;
                $newfile = $httpadapter->getFileName();
                var_dump($newfile);
            }


        }
    }


    die();
}

Solution

  • I see this just remaining move uploaded file to destination. $httpadapter->receive() just for checking file uploaded or not. It was not purposed for moving uploaded files. You should use Filter for this, and call File\Rename filter.

    $httpadapter->setDestination('./data/stockhelper');
    $httpadapter->setValidators(array($filesize, $extension), $files['file']['name']);
    $httpadapter->addFilter('File\Rename', array('target' => $httpadapter->getDestination() . DIRECTORY_SEPARATOR . sha1_file($files['file']['name']) . '.xls', 'overwrite' => true));
    
    if (!$adapter->receive()) {
        // uploading error
        $messages = $httpadapter->getMessages();
    } else {
        $newfile  = $httpadapter->getFileName();
    }