@raphael_tillman
To handle file uploads in Phalcon, follow these steps:
- Create a form in your Phalcon application with an input element of type "file". This should be done in a view file as follows:
- In your controller, use the request object to handle the file upload. The request object contains all the information about the uploaded file. You can access the uploaded file using the "getUploadedFile" method as follows:
1
2
3
4
5
6
7
8
|
public function uploadAction()
{
if ($this->request->hasFiles() == true) {
foreach ($this->request->getUploadedFiles() as $file) {
// handle the uploaded file here
}
}
}
|
- Once you have the uploaded file, you can save it in a directory on your system. You can use the "moveTo" method to move the uploaded file to the desired location as follows:
1
|
$file->moveTo('/path/to/uploaded/files/' . $file->getName());
|
- You may also want to validate the uploaded file before saving it. You can use the "getSize" and "getExtension" methods to perform validation as follows:
1
2
3
4
5
6
7
|
if ($file->getSize() > 1048576) {
// file size exceeds 1MB
}
if ($file->getExtension() != "jpg" && $file->getExtension() != "png") {
// file extension not supported
}
|
Note: It is important to set the "enctype" attribute of the form to "multipart/form-data" to enable file uploads.