public static function fromUpload($name, $deleteAfter = true)
{
$webroot = Yii::getAlias('@webroot');
$uploadImage = UploadedFile::getInstanceByName($name);
$instance = new Image();
$instance->ext = pathinfo($uploadImage->name, PATHINFO_EXTENSION);
$instance->title = basename($uploadImage->name);
$instance->size = $uploadImage->size;
if ($instance->size == 0)
return null;
if ($instance->save()) {
$url = strtr('/media/images/{date}/{id}/{file}', ['{date}' => date('Y/m/d'), '{id}' => $instance->id, '{file}' => $uploadImage->name]);
$destPath = $webroot . $url;
FileHelper::createDirectory(dirname($destPath), 0777);
if ($uploadImage->saveAs($destPath, $deleteAfter)) {
list($width, $height) = self::dimension($destPath);
$instance->setAttributes([
'url' => $url,
'width' => $width,
'height' => $height,
'mime' => $uploadImage->type,
'name' => $uploadImage->name,
'title' => '',
]);
$instance->update(false);
return $instance;
} else {
$instance->delete();
return null;
}
}
return null;
}