-
Notifications
You must be signed in to change notification settings - Fork 272
/
Upload.php
51 lines (43 loc) · 1.67 KB
/
Upload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
namespace yii\easyii\helpers;
use Yii;
use yii\web\UploadedFile;
use \yii\web\HttpException;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
use yii\helpers\FileHelper;
use yii\helpers\Url;
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 = Yii::getAlias('@webroot').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('@webroot'), '', $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;
}
}