Created
June 13, 2014 00:42
-
-
Save trfiladelfo/ff5c4fd4fc2db9ce8d14 to your computer and use it in GitHub Desktop.
Upload de arquivos no cakephp...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
App::uses('HttpSocket', 'Network/Http'); | |
App::uses('File', 'Utility'); | |
App::uses('Folder', 'Utility'); | |
class FileWriter { | |
public function write($image=array(), $filename=null) { | |
if(!$image || ($image['error']!=0) && ($image['size']==0)) { | |
throw new NotImplementedException('Image not found.'); | |
} | |
$directory = 'files/upload/'. (new DateTime())->format('Y').'/'; | |
$folder = new Folder(); | |
if (!is_dir($directory)){ | |
$folder->create($directory); | |
} | |
$image_info = pathinfo($directory.$image['name']); | |
if(!$filename) { | |
$name = strtolower(Inflector::slug($image_info['filename'],'_')); | |
} else { | |
$name = strtolower(Inflector::slug($filename,'_')); | |
} | |
$name = $name . '.' . $image_info['extension']; | |
$sequence = 2; | |
while (file_exists($directory.$name)) { | |
if(!$filename) { | |
$name = strtolower(Inflector::slug($image_info['filename'] . '(' . $sequence . ')','_')); | |
} else { | |
$name = strtolower(Inflector::slug($filename . '(' . $sequence . ')','_')); | |
} | |
$name = $name . '.' . $image_info['extension']; | |
$sequence++; | |
} | |
$image['name'] = $name; | |
$directory = $directory.$image['name']; | |
$file_output = new File($image['tmp_name']); | |
$file_output->copy($directory); | |
$file_output->close(); | |
return $directory; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
App::uses('AppModel', 'Model'); | |
App::import('Vendor', 'IOStream/FileWriter'); | |
class TestModel extends AppModel { | |
public function beforeSave($options = array()) { | |
if(!empty($this->data['Movie']['image']['name'])) { | |
$FileWriter = new FileWriter(); | |
$path = $FileWriter->write($this->data['Movie']['image']); | |
$this->data['Movie']['image'] = Router::url('/', true) . $path; | |
} else { | |
unset($this->data['Movie']['image']); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basta criar o arquivo FileWriter na pasta Vendor, e depois colocar os importa na sua classe Model.