add Image and Upload helper classes
This commit is contained in:
50
common/components/Upload.php
Normal file
50
common/components/Upload.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
namespace common\components;
|
||||
|
||||
use Yii;
|
||||
use yii\web\UploadedFile;
|
||||
use \yii\web\HttpException;
|
||||
use yii\helpers\Inflector;
|
||||
use yii\helpers\StringHelper;
|
||||
use yii\helpers\FileHelper;
|
||||
|
||||
class Upload
|
||||
{
|
||||
public static $UPLOADS_DIR = 'uploads';
|
||||
|
||||
public static function file(UploadedFile $fileInstance, $dir = '', $namePostfix = true)
|
||||
{
|
||||
$fileName = Upload::getUploadPath($dir) . DIRECTORY_SEPARATOR . Upload::getFileName($fileInstance, $namePostfix);
|
||||
|
||||
if(!$fileInstance->saveAs($fileName)){
|
||||
throw new HttpException(500, 'Cannot upload file "'.$fileName.'". Please check write permissions.');
|
||||
}
|
||||
return Upload::getLink($fileName);
|
||||
}
|
||||
|
||||
static function getUploadPath($dir)
|
||||
{
|
||||
$uploadPath = $dir = Yii::getAlias('@frontend/web').DIRECTORY_SEPARATOR.self::$UPLOADS_DIR.($dir ? DIRECTORY_SEPARATOR.$dir : '');
|
||||
if(!FileHelper::createDirectory($uploadPath)){
|
||||
throw new HttpException(500, 'Cannot create "'.$uploadPath.'". Please check write permissions.');
|
||||
}
|
||||
return $uploadPath;
|
||||
}
|
||||
|
||||
static function getLink($fileName)
|
||||
{
|
||||
return str_replace('\\', '/', str_replace(Yii::getAlias('@frontend/web'), '', $fileName));
|
||||
}
|
||||
|
||||
static function getFileName($fileInstanse, $namePostfix = true)
|
||||
{
|
||||
$baseName = str_ireplace('.'.$fileInstanse->extension, '', $fileInstanse->name);
|
||||
$fileName = StringHelper::truncate(Inflector::slug($baseName), 32, '');
|
||||
if($namePostfix || !$fileName) {
|
||||
$fileName .= ($fileName ? '-' : '') . substr(uniqid(md5(rand()), true), 0, 10);
|
||||
}
|
||||
$fileName .= '.' . $fileInstanse->extension;
|
||||
|
||||
return $fileName;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user