File upload code is created and working fine but i want optional file upload

File upload code is created and working fine but I wanted to optionally upload file then where to change so that can without uploading file submit form Please Let me know .

$attachment = $this->request->getData('img_url');
            
            $name = $attachment->getClientFilename();
            $size = $attachment->getSize();
            $tmpName = $attachment->getStream()->getMetadata('uri');
            $error = $attachment->getError();
            $subCollection->created_at = date('Y-m-d H:i:s');
           
            $targetPath = "upload/collections/".$name;
            if(move_uploaded_file($tmpName,  $targetPath)){
            $subCollection = $this->SubCollections->patchEntity($subCollection, $this->request->getData());
            $subCollection->img_url = $name;
            
            if ($this->SubCollections->save($subCollection)) {
                $this->Flash->success(__('The sub collection has been saved.'));
                 $imgpath = 'upload/collections/' . $subCollection->img_url;
                    if (file_exists($imgpath)) {
                        unlink($imgpath);
                    }
                return $this->redirect(['action' => 'index']);
             }

I see the code, but I have no idea what your question is?

Check the docs - you can either check the error code returned (4 = empty)

or you can use

$attachment = $this->request->getUploadedFile('attachment');

Which returns either the file data, or null if no file was chosen.

Then you can check

if ( ! empty($attachment) ) { // do the upload
https://book.cakephp.org/4/en/controllers/request-response.html#file-uploads

1 Like

This was solved problem