Skip to content

Instantly share code, notes, and snippets.

@jbanety
Last active August 29, 2015 14:22
Show Gist options
  • Save jbanety/d9dee970d4d8a5f6de60 to your computer and use it in GitHub Desktop.
Save jbanety/d9dee970d4d8a5f6de60 to your computer and use it in GitHub Desktop.
etd upload ajax
/**
* Méthode pour uploader un avatar en AJAX.
*
* @return \stdClass
*/
public function uploadavatar() {
// Init
$result = new \stdClass();
$app = $this->getApplication();
$input = $this->getInput();
$text = (new LanguageFactory())->getText();
$filesInput = new Files();
$logo = $filesInput->get('avatarFile_upload', array(), 'array');
$recordId = $input->get('id', 0, 'uint');
$imagesDir = JPATH_MEDIA . "/images/users";
//@TODO: a mettre dans la conf de l'appli
$sizes = [
'40' => [ 'method' => 'crop_inside', 'size' => '40x40' ],
'50' => [ 'method' => 'crop_inside', 'size' => '50x50' ],
'60' => [ 'method' => 'crop_inside', 'size' => '60x60' ],
'80' => [ 'method' => 'crop_inside', 'size' => '80x80' ],
'directory' => [ 'method' => 'crop_inside', 'size' => '100x100' ],
'profile' => [ 'method' => 'crop_inside', 'size' => '160x160' ],
'bg' => [ 'method' => 'crop_inside', 'size' => '500x1000' ]
];
// On contrôle les droits de modification.
if (!$this->allowEdit($recordId)) {
$result->message = $text->translate('APP_ERROR_UNAUTHORIZED_ACTION');
$result->status = 403;
return $result;
}
if (!empty($logo['name']) && !empty($logo['tmp_name'])) {
$isError = false;
$errorMsg = "";
// On contrôle que c'est bien une image.
if (!in_array($logo['type'], array(
'image/png',
'image/gif',
'image/jpeg'
))
) {
$isError = true;
$errorMsg = 'APP_ERROR_UPLOAD_BAD_MIME_TYPE';
}
if ($logo['error'] == 1 || $logo['size'] > ($app->get('upload_maxsize', 0) * 1024 * 1024)) {
$isError = true;
$errorMsg = 'APP_ERROR_UPLOAD_FILE_TOO_LARGE';
}
// Si une erreur s'est produite.
if ($isError) {
// On renvoie vers le formulaire.
$result->error = $text->translate($errorMsg);
return $result;
}
// On récupère les exceptions grâce au bloc try..catch pour les renvoyer en JSON.
try {
// On supprime l'ancien logo si besoin.
$table = $this->getTable();
if ($recordId > 0 && $table->load($recordId) && !empty($table->profile->avatarFile)) {
// Bloc try..catch pour éviter les erreurs en cas d'échec de suppression.
try {
File::delete(Folder::files($imagesDir, $table->profile->avatarFile . ".*?", false, true));
} catch (\Exception $e) {
}
}
// On génère le nom de l'image.
$name = $this->genRandomFilename();
$original_path = Path::clean($imagesDir . "/" . $name . "." . pathinfo($logo['name'], PATHINFO_EXTENSION));
// On déplace le fichier dans le dossier.
File::upload($logo['tmp_name'], $original_path);
// On génère toutes les images.
$image = new ImageUtility();
$image->generateImageSizes($original_path, $sizes);
// On sauvegarde le nom dans la base.
$result->name = $name;
} catch (\Exception $e) {
$result->error = $e->getMessage();
}
}
return $result;
}
/**
* Génère un nom de fichier aléatoire.
*
* @param integer $length La taille du nom de fichier.
*
* @return string Nom de fichier aléatoire.
*/
protected function genRandomFilename($length = 8) {
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$base = strlen($salt);
$makepass = '';
$random = Crypt::genRandomBytes($length + 1);
$shift = ord($random[0]);
for ($i = 1; $i <= $length; ++$i) {
$makepass .= $salt[($shift + ord($random[$i])) % $base];
$shift += ord($random[$i]);
}
return $makepass;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment