CakePHP File upload


In CakePHP, you can use the Cake\Http\Client\FormData class to upload files to the server. Here’s an example of how you can use this class to upload a file in a CakePHP application:

  1. In your form template, add a file input field:
echo $this->Form->create($article, ['type' => 'file']);
echo $this->Form->control('file', ['type' => 'file']);
echo $this->Form->button(__('Submit'));
echo $this->Form->end();
  1. In your controller action, check if the form was submitted and the file field is not empty:
if ($this->request->is('post') && !empty($this->request->getData('file'))) {
    // File was submitted
  1. Create a new instance of Cake\Http\Client\FormData and add the file to it:
$formData = new \Cake\Http\Client\FormData();
$formData->addFile('file', $this->request->getData('file.tmp_name'));
  1. Use the Cake\Http\Client class to send a POST request to the server, including the FormData object as the body of the request:
$http = new \Cake\Http\Client();
$response = $http->post('/upload', $formData);