I am trying to send data from a react native application to cakephp. 4.x as a backend, I am sending data from a form with a photo. My problem is the following the form data is saved in the database except the image. here is my backend code
public function addOffre()
{
// Désactiver le layout et l'auto-render
$this->viewBuilder()->disableAutoLayout();
$this->autoRender = false;
// Charger le modèle Offres
$offresTable = $this->getTableLocator()->get('Offres');
// Récupérer les données de la requête et les fichiers téléchargés
$offreData = $this->request->getData();
Log::debug('Data: ' . json_encode($this->request->getData()));
$uploadedFiles = $this->request->getUploadedFiles();
//Log::debug('Uploaded files: ' . json_encode($uploadedFiles));
$fileNames = [];
// Gérer le téléchargement des fichiers
if (!empty($uploadedFiles['File'])) {
$files = $uploadedFiles['File'];
// Si un seul fichier est envoyé, le convertir en tableau pour itération
if (!is_array($files)) {
$files = [$files];
}
// Sauvegarder chaque fichier
foreach ($files as $file) {
//Log::debug('FileError: ' . json_encode($file->getError()));
if ($file->getError() === UPLOAD_ERR_OK) {
$targetDir = WWW_ROOT . 'uploads' . DS . 'Offres' . DS;
if (!is_dir($targetDir)) {
mkdir($targetDir, 0777, true);
}
$fileSize = $file->getSize();
Log::debug('Size: ' . $fileSize);
$fileName = time() . '_' . $file->getClientFilename();
$targetFile = $targetDir . $fileName;
Log::debug('Chemin de destination: ' . $targetFile);
if ($file->moveTo($targetFile)) {
$fileNames[] = 'uploads/Offres/' . $fileName;
Log::debug('File moved: ' . $fileName);
} else {
Log::error('Failed to move file: ' . $file->getClientFilename().', Error '. $file->getError());
}
} else {
Log::error('File upload error: ' . $file->getError());
}
}
}
$offreData['filename'] = implode(',', $fileNames);
$offre = $offresTable->newEmptyEntity();
$offre = $offresTable->patchEntity($offre, $offreData);
Log::debug('File moved: ' . $offre);
if ($offresTable->save($offre)) {
$arrReturn = ['status' => 'ok'];
} else {
$arrReturn = ['status' => 'false'];
}
echo json_encode($arrReturn);
}
the debug of $this->request->getUploadedFiles(); gives {} but when Log::debug('Size: ’ . $file->getSize()); gives the file size Log::debug('Size: ’ . $file->getClientFilename()); gives the file name
I need help to enlighten me, or I made mistakes,
thanks in advance