Skip to content

Instantly share code, notes, and snippets.

@Theaxiom
Created November 3, 2016 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Theaxiom/2187cd4db324cebb71ee074ff2fae981 to your computer and use it in GitHub Desktop.
Save Theaxiom/2187cd4db324cebb71ee074ff2fae981 to your computer and use it in GitHub Desktop.
nameCallback not renaming photos
$this->addBehavior('Josegonzalez/Upload.Upload', [
// You can configure as many upload fields as possible,
// where the pattern is `field` => `config`
//
// Keep in mind that while this plugin does not have any limits in terms of
// number of files uploaded per request, you should keep this down in order
// to decrease the ability of your users to block other requests.
'photo' => [
'fields' => [
// if these fields or their defaults exist
// the values will be set.
'dir' => 'photo_dir', // defaults to `dir`
'size' => 'photo_size', // defaults to `size`
],
'nameCallback' => [$this, 'renameUploadedPhoto'],
// This can also be in a class that implements
// the TransformerInterface or any callable type.
'transformer' => function (\Cake\Datasource\RepositoryInterface $table, \Cake\Datasource\EntityInterface $entity, $data, $field, $settings) {
// get the extension from the file
// there could be better ways to do this, and it will fail
// if the file has no extension
$extension = pathinfo($data['name'], PATHINFO_EXTENSION);
// Store the thumbnail in a temporary file
$tmp = tempnam(sys_get_temp_dir(), 'upload') . '.' . $extension;
// Use the Imagine library to DO THE THING
$size = new \Imagine\Image\Box(40, 40);
$mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine = new \Imagine\Gd\Imagine();
// Save that modified file to our temp file
$imagine->open($data['tmp_name'])
->thumbnail($size, $mode)
->save($tmp);
// Now return the original *and* the thumbnail
return [
$data['tmp_name'] => $data['name'],
$tmp => 'thumbnail-' . $data['name'],
];
},
],
]);
public function renameUploadedPhoto(array $data, array $settings)
{
$ext = substr(strrchr($data['name'], '.'), 1);
return Text::uuid() . '.' . $ext;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment