17
17
*/
18
18
class FileModel extends \yii \db \ActiveRecord
19
19
{
20
+ /**
21
+ * @var string
22
+ */
23
+ public static $ defaultUploadPath = '@runtime/upload ' ;
24
+ /**
25
+ * @var integer
26
+ */
27
+ public static $ defaultDirectoryLevel = 1 ;
20
28
/**
21
29
* @var UploadedFile
22
30
*/
@@ -25,15 +33,15 @@ class FileModel extends \yii\db\ActiveRecord
25
33
/**
26
34
* @var string Upload path
27
35
*/
28
- public $ uploadPath = ' @runtime/upload ' ;
36
+ public $ uploadPath ;
29
37
30
38
/**
31
39
* @var integer the level of sub-directories to store uploaded files. Defaults to 1.
32
40
* If the system has huge number of uploaded files (e.g. one million), you may use a bigger value
33
41
* (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
34
42
* is not over burdened with a single directory having too many files.
35
43
*/
36
- public $ directoryLevel = 1 ;
44
+ public $ directoryLevel ;
37
45
38
46
/**
39
47
* @var \Closure
@@ -56,22 +64,22 @@ public function rules()
56
64
return [
57
65
[['file ' ], 'required ' ],
58
66
[['file ' ], 'file ' , 'skipOnEmpty ' => false ],
59
- [['uploadPath ' ], 'required ' , 'when ' => function ($ obj ) {
60
- return empty ($ obj ->filename );
61
- }],
67
+ [['uploadPath ' ], 'default ' , 'value ' => static ::$ defaultUploadPath ],
62
68
[['name ' , 'size ' ], 'default ' , 'value ' => function ($ obj , $ attribute ) {
63
69
return $ obj ->file ->$ attribute ;
64
70
}],
65
71
[['type ' ], 'default ' , 'value ' => function () {
66
72
return FileHelper::getMimeType ($ this ->file ->tempName );
67
73
}],
68
74
[['filename ' ], 'default ' , 'value ' => function () {
75
+ $ level = $ this ->directoryLevel === null ? static ::$ defaultDirectoryLevel : $ this ->directoryLevel ;
69
76
$ key = md5 (microtime () . $ this ->file ->name );
70
77
$ base = Yii::getAlias ($ this ->uploadPath );
71
- if ($ this -> directoryLevel > 0 ) {
72
- for ($ i = 0 ; $ i < $ this -> directoryLevel ; ++$ i ) {
73
- if (($ prefix = substr ($ key , $ i + $ i , 2 )) !== false ) {
78
+ if ($ level > 0 ) {
79
+ for ($ i = 0 ; $ i < $ level ; ++$ i ) {
80
+ if (($ prefix = substr ($ key , 0 , 2 )) !== false ) {
74
81
$ base .= DIRECTORY_SEPARATOR . $ prefix ;
82
+ $ key = substr ($ key , 2 );
75
83
}
76
84
}
77
85
}
0 commit comments