Saturday, March 27, 2010

Uploading files

CREATE TABLE my_files (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(75) NOT NULL,
type VARCHAR(255) NOT NULL,
size INT(11) NOT NULL,
data MEDIUMBLOB NOT NULL,
created DATETIME,
modified DATETIME,
PRIMARY KEY (id)
);


// app/models/my_file.php
class MyFile extends AppModel {
var $name = 'MyFile';
}


// app/views/my_files/add.ctp (Cake 1.2)
echo $form->create('MyFile', array('action' => 'add', 'type' => 'file'));
echo $form->file('File');
echo $form->submit('Upload');
echo $form->end();
?>

// app/views/my_files/add.thtml (Cake 1.1)

file('File'); ?>
submit('Upload'); ?>



// app/controllers/my_files_controller.php (Cake 1.2)
class MyFilesController extends AppController {
function add() {
if (!empty($this->data) &&
is_uploaded_file($this->data['MyFile']['File']['tmp_name'])) {
$fileData = fread(fopen($this->data['MyFile']['File']['tmp_name'], "r"),
$this->data['MyFile']['File']['size']);

$this->data['MyFile']['name'] = $this->data['MyFile']['File']['name'];
$this->data['MyFile']['type'] = $this->data['MyFile']['File']['type'];
$this->data['MyFile']['size'] = $this->data['MyFile']['File']['size'];
$this->data['MyFile']['data'] = $fileData;

$this->MyFile->save($this->data);

$this->redirect('somecontroller/someaction');
}
}
}

// app/controllers/my_files_controller.php (Cake 1.1)
class MyFilesController extends AppController {
function add() {
if (!empty($this->params['form']) &&
is_uploaded_file($this->params['form']['File']['tmp_name'])) {
$fileData = fread(fopen($this->params['form']['File']['tmp_name'], "r"),
$this->params['form']['File']['size']);
$this->params['form']['File']['data'] = $fileData;

$this->MyFile->save($this->params['form']['File']);

$this->redirect('somecontroller/someaction');
}
}
}



and for download that file:

function download($id) {
Configure::write('debug', 0);
$file = $this->MyFile->findById($id);

header('Content-type: ' . $file['MyFile']['type']);
header('Content-length: ' . $file['MyFile']['size']);
header('Content-Disposition: attachment; filename="'.$file['MyFile']['name'].'"');
echo $file['MyFile']['data'];

exit();
}

No comments:

Post a Comment