Skip to content

Commit a3a9b5b

Browse files
committed
change use default upload path
1 parent f431814 commit a3a9b5b

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

FileModel.php

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@
1717
*/
1818
class FileModel extends \yii\db\ActiveRecord
1919
{
20+
/**
21+
* @var string
22+
*/
23+
public static $defaultUploadPath = '@runtime/upload';
24+
/**
25+
* @var integer
26+
*/
27+
public static $defaultDirectoryLevel = 1;
2028
/**
2129
* @var UploadedFile
2230
*/
@@ -25,15 +33,15 @@ class FileModel extends \yii\db\ActiveRecord
2533
/**
2634
* @var string Upload path
2735
*/
28-
public $uploadPath = '@runtime/upload';
36+
public $uploadPath;
2937

3038
/**
3139
* @var integer the level of sub-directories to store uploaded files. Defaults to 1.
3240
* If the system has huge number of uploaded files (e.g. one million), you may use a bigger value
3341
* (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
3442
* is not over burdened with a single directory having too many files.
3543
*/
36-
public $directoryLevel = 1;
44+
public $directoryLevel;
3745

3846
/**
3947
* @var \Closure
@@ -56,22 +64,22 @@ public function rules()
5664
return [
5765
[['file'], 'required'],
5866
[['file'], 'file', 'skipOnEmpty' => false],
59-
[['uploadPath'], 'required', 'when' => function($obj) {
60-
return empty($obj->filename);
61-
}],
67+
[['uploadPath'], 'default', 'value' => static::$defaultUploadPath],
6268
[['name', 'size'], 'default', 'value' => function($obj, $attribute) {
6369
return $obj->file->$attribute;
6470
}],
6571
[['type'], 'default', 'value' => function() {
6672
return FileHelper::getMimeType($this->file->tempName);
6773
}],
6874
[['filename'], 'default', 'value' => function() {
75+
$level = $this->directoryLevel === null ? static::$defaultDirectoryLevel : $this->directoryLevel;
6976
$key = md5(microtime() . $this->file->name);
7077
$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) {
7481
$base .= DIRECTORY_SEPARATOR . $prefix;
82+
$key = substr($key, 2);
7583
}
7684
}
7785
}

0 commit comments

Comments
 (0)