Wednesday, January 24, 2007

File uploads with CakePHP

I wanted to upload a file and attach it to my object, but couldn't find a nice enough solution for it out there, so I created my own method, and I must say I'm quite happy with the results.

In my controller, I just added a method called encodeFile that take 2 parameters, the PHP file upload array, and a target variable reference;

   
function encodeFile($arr, &$dest)
{
switch($arr["error"]) {
case 0: // OK!
$fileData = fread(fopen($arr['tmp_name'], "r"),
$arr['size']);
if(!$fileData)
return "Could not read file from disk";
$dest = base64_encode($fileData);
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
return "The file is too big.";
case UPLOAD_ERR_PARTIAL:
case UPLOAD_ERR_NO_FILE:
return "The file was not uploaded.";
case UPLOAD_ERR_NO_TMP_DIR:
case UPLOAD_ERR_CANT_WRITE:
return "A configuration error occured";
default:
return "An unknown error occured.";
}

return true;
}


Then, in my add() method, I can use the function like this:

$ret = $this->encodeFile($this->params["form"]["File"], $this->data["MyModel"]["File"]);
if($ret !== true) {
$this->Session->setFlash('File problems: ' . $ret);
} else {
if($this->MyModel->save($this->data)) {
...

I also added a controller method to view the image:

function image($id)
{
$this->layout = "empty";
$o = $this->MyModel->read(null, $id);
Header("Content-type: image");
echo base64_decode($o["MyModel"]["File"]);
}

No comments:

Post a Comment