I can upload files into desired folder. When delete record, the file also deleted as expected.
However, I can not delete the file only, while keeping the record.
I have Covid-Test model, and result_file is the field for upload file.
I want user to be able to delete result_file, or update another file.
What I did is creating a link to delete_file controller action as below, but the file is not deleted.
Could someone help me out with this? Documentation did not mention about deleting the uploaded file.
public function deleteFile($id = null)
{
$covidTest = $this->CovidTests->get($id);
if (!is_null($covidTest->result_file) && $covidTest->result_file != ''){
$file = new File(CovidTestsTable::UPLOAD_DIR . $covidTest->result_file);
if ($file->exists()){
$file->delete();
$this->Flash->success('File deleted !');
}
} else {
$this->Flash->success('No uploaded file exist !');
}
$covidTest->result_file = null;
$this->CovidTests->save($covidTest);
return $this->redirect($this->referer());
}
Thanks Raul338 for your response, but I don’t get why you need to remove the action.
As far as I understand, 1 record can only have 1 uploaded file, mapped to a field of the record.
So if you want to update another file, in my case, user upload test result with wrong file, he need to remove that uploaded file, then upload new one.
In my view, I have a check if the field is null, then update form has input control for upload, else, just display a link to delete the file.
And I am currently have problem with deleting the uploaded file. Will check the path once again.
Finally, I have to accept that uploading and deleting using 2 different path.
My new deleteFile function works now: by adding ROOT . DS . in front of file path.
public function deleteFile($id = null)
{
$covidTest = $this->CovidTests->get($id);
if (!is_null($covidTest->result_file) && $covidTest->result_file != ''){
$file = new File(ROOT . DS . CovidTestsTable::UPLOAD_DIR . $covidTest->result_file);
if ($file->exists()){
$file->delete();
$this->Flash->success('File deleted !');
}
} else {
$this->Flash->success('No uploaded file exist !');
}
$covidTest->result_file = null;
$this->CovidTests->save($covidTest);
return $this->redirect($this->referer());
}