Skip to content

Instantly share code, notes, and snippets.

@frostbitten
Last active June 13, 2016 18:28
Show Gist options
  • Save frostbitten/1e2a1c316b312a4daacaa41d95f4d6e8 to your computer and use it in GitHub Desktop.
Save frostbitten/1e2a1c316b312a4daacaa41d95f4d6e8 to your computer and use it in GitHub Desktop.
simple uploader integration
"codeguy/upload":"~1",
<?php
if (!$app->user->checkAccess('upload_user_files')){
$app->notFound();
}
if( $what == "media" ){ // this can be accomplished better by putting the following logic into a controller
if (!$app->user->checkAccess('upload_user_files_media')){
$app->notFound();
}
$post = $app->request->post();
// Ensure file is no larger than 5M (use "B", "K", M", or "G")
$max_upload_size = '10M';
$save_location = $app->config('userfiles.path').DIRECTORY_SEPARATOR.'medias'.DIRECTORY_SEPARATOR.$app->user->id;
if(!is_dir($save_location) && !mkdir($save_location,0774,true)){
$app->halt(400);
// destination folder doesn't exist and could not be created. probably privilege issue
}
$storage = new \Upload\Storage\FileSystem($save_location);
$file = new \Upload\File('file', $storage);
$oldname = $file->getName();
// Optionally you can rename the file on upload
$new_filename = uniqid();
$file->setName($new_filename);
// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$file->addValidations(array(
//You can also add multi mimetype validation
new \Upload\Validation\Mimetype(array('image/png', 'image/jpg', 'image/jpeg', 'image/gif')),
new \Upload\Validation\Size($max_upload_size)
));
// Access data about the file that has been uploaded
$data = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
// Try to upload file
try {
// Success!
$file->upload();
$upload_success = true;
} catch (\Exception $e) {
// Fail!
$errors = $file->getErrors();
error_log('failed saving file:'.print_r(['e'=>$e,'file errors'=>$errors],1));
$upload_success = false;
$app->halt(500);
}
if($upload_success){
//save the media entry
$media_entry = new UserMedia([
'user_id' => $app->user->id,
'media_type'=>'uploaded-media',
'source'=>$data['name']
]);
$media_entry->save();
//record the user event
$event = new UserEvent([
'user_id' => $app->user->id,
"event_type" => "user_image_uploaded",
"description" => json_encode([
'filedata'=>$data,
'UserMedia_id'=>$media_entry->id
])
]);
$event->save();
echo $media_entry->toJson();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment