We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to get an uploaded file directly

$this->request->getUploadedFiles() return an array of all uploaded file. Is there any clean way to access an uploaded file using its field name. It seems there is not method similar to: $this->request->getUploadedFile('avatar');



33.8k

As you say, it returns an array ( https://github.com/phalcon/cphalcon/blob/2.0.0/phalcon/http/request.zep#L759 ): the problem is that is an array of Files ( https://docs.phalcon.io/es/latest/api/Phalcon_Http_Request_File.html ). So, unless it is changed, you should create your own function that searchs for the specific file.



22.1k

Finally I used the following to access a single file: $file=new Phalcon\Http\Request\File($_FILES[$fieldName]); IMHO $this->request->hasFile($fileName) and $this->request->getFile($fileNmae) should be added to Phalcon\Http\Request.

edited Dec '20

if($this->request->hasFiles(true))
{
    foreach($this->request->getUploadedFiles(true) as $upload)
    {
        //check form input name attribute getKey() 
        //<input type="file" name="avatar" ....>
        if($upload->getKey() === 'avatar')
        {
            //...
            if($upload->moveTo('avatars/'.$upload->getName()))
            {
                //...
            }
        }
    }
}